Sql server 2012 SQL,其中包含二进制(n)列

Sql server 2012 SQL,其中包含二进制(n)列,sql-server-2012,Sql Server 2012,我有一个存储过程: ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification] @ContentJsonHash BINARY(32) AS DECLARE @NotificationId INT; SET @NotificationId = (SELECT @NotificationId FROM dbo.tblNotifications n

我有一个存储过程:

ALTER PROCEDURE [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS
    DECLARE @NotificationId INT;

    SET @NotificationId = (SELECT @NotificationId
                           FROM dbo.tblNotifications n
                           WHERE n.ContentJsonHash = @ContentJsonHash);

    IF @NotificationId IS NOT NULL  
    BEGIN
        -- Increment Count
    END
    ELSE
    BEGIN
         -- Insert new row.
    END
它应该检查散列是否已经存在,如果已经存在,则增加该行的计数,否则插入该行。但是,它从未找到散列和相应的
NotificationId
<代码>通知ID始终为空

如果我运行它两次,向它传递相同的数据(一个C数组
字节[32]
)。它从未找到相同的
NotificationId
,我最终得到了重复的条目

e、 g

我能不能在像这样的二进制(n)字段上进行比较,其中n.ContentJsonHash=@ContentJsonHash

C#代码:

我还尝试从SQL调用存储过程,如下所示:

exec dbo.spUpdateOrInsertNotification 'foo', 'bar',  0, 
                                      '2017-12-05 15:23:41.207', '{}',
                              0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
调用两次将返回两行:(

我可以做到这一点,这是可行的,硬编码的二进制字段,我想检查

select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A

二进制比较可能很棘手。如果您使用的是真正的二进制列,我相信长度也会起作用。因此,即使这些字节相同,长度不同,比较也会是错误的。一种简单的方法是将它们转换为字符串:

alter procedure [dbo].[spUpdateOrInsertNotification]
    @ContentJsonHash BINARY(32)
AS

DECLARE @NotificationId INT;
SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

IF @NotificationId IS NOT NULL  
BEGIN
   -- Increment Count
END
ELSE
BEGIN
   -- Insert new row.
END

我有一个不该有符号的地方

SET @NotificationId = (SELECT @NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));
应该是

SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));

我觉得很愚蠢,因为我没有早点注意到这一点:(

那应该很好。列的确切类型是什么?如何从C#调用sp?)(还要记住,可以在读取@NotificationId并使用它的过程中插入一行)@Alex K。我添加了C#,也从sql调用它
SET @NotificationId = (SELECT @NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));
SET @NotificationId = (SELECT NotificationId
                       FROM dbo.tblNotifications n
                       WHERE convert(varchar(32), n.ContentJsonHash, 2) = convert(varchar(32), @ContentJsonHash, 2));