我有一个存储过程:
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它应该检查Hash是否已经存在,如果存在,则递增该行的计数,否则插入该行。但是,它永远找不到散列和相应的NotificationId。NotificationId始终为空。
如果我运行两次,向它传递相同的数据(一个C#数组byte[32])。它永远找不到相同的NotificationId,而我最终只能放入重复的条目。
例如:
NotificationId | ContentJsonHash
9 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A
10 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A我不能对像这样的二进制(N)字段进行比较吗?WHERE n.ContentJsonHash = @ContentJsonhash?
C#代码:
using (var conn = new SqlConnection(Sql.ConnectionString))
{
await conn.OpenAsync();
using (var cmd = new SqlCommand(Sql.SqlUpdateOrInsertNotification, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Source", notificationMessage.Source);
cmd.Parameters.AddWithValue("@Sender", notificationMessage.Sender);
cmd.Parameters.AddWithValue("@NotificationType", notificationMessage.NotificationType);
cmd.Parameters.AddWithValue("@ReceivedTimestamp", notificationMessage.Timestamp);
cmd.Parameters.AddWithValue("@ContentJSon", notificationMessage.NotificationContent);
cmd.Parameters.AddWithValue("@ContentJsonHash", notificationMessage.ContentHashBytes);
await cmd.ExecuteNonQueryAsync();
}
}我还尝试过像这样从SQL中调用存储过程:
exec dbo.spUpdateOrInsertNotification 'foo', 'bar', 0,
'2017-12-05 15:23:41.207', '{}',
0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A调用这两次将返回2行:(
我可以做到这一点,这是有效的,硬编码我想要检查的二进制字段
select *
from dbo.tblNotifications
where ContentJsonhash = 0xB966C33517993003D789EDF78DA20C4C491617F8F42F76F48E572ACF8EDFAC2A发布于 2017-12-06 16:20:39
我有一个@,我不应该有一个&符号。
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));我太傻了,没有早点注意到这一点:
发布于 2017-12-06 00:48:31
二进制比较可能很棘手。如果你使用的是真正的二进制列,我相信长度也会起作用。因此,即使这些字节相同,而长度不同,比较也是假的。一种简单的方法是将它们转换为字符串:
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.
ENDhttps://stackoverflow.com/questions/47658412
复制相似问题