SQL完全匹配为NULL或非null列

时间:2018-07-25 15:12:23

标签: c# sql

我必须根据行是否存在来删除或插入。但是其中一列可能是NULL,因此,如果我传递的值是Col 1: 123, Col 2: 345, Col 3: NULL,并且此行存在,请删除该行,然后插入。问题是DBNull.Value与空列不匹配。

查询

@"IF EXISTS(SELECT * FROM auth.UserPermissions ur WHERE ur.UserGroupId = @UserGroupId AND ur.ClientId = @ClientId AND ur.PermissionId = @PermissionId)
DELETE FROM auth.UserPermissions WHERE UserGroupId = @UserGroupId AND ClientId = @ClientId AND PermissionId = @PermissionId
ELSE
INSERT INTO auth.UserPermissions (ClientId, UserGroupId, PermissionId)
VALUES (@ClientId, @UserGroupId, @PermissionId)";

可能为NULL的列为ClientId。我不能使用AND (ur.ClientId = @ClientId OR ur.ClientId IS NULL),因为如果我传递两个对象,其中Col 1: 123, Col 2: 345, Col 3: NULLCol 1: 123, Col 2: 345, Col 3: 567用于插入,我将插入第一个是 insert ,第二个是sql IF语句将返回true并删除ClientId NULL ,而我将567传递给ClientId

我该如何实现?

还有我的 cs

var clientId = string.IsNullOrEmpty(_obj.ClientId) ? (object)DBNull.Value : _obj.ClientId;

string _query = @"IF EXISTS(SELECT * FROM auth.UserPermissions ur WHERE ur.UserGroupId = @UserGroupId AND ur.ClientId = @ClientId AND ur.PermissionId = @PermissionId)
DELETE FROM auth.UserPermissions WHERE UserGroupId = @UserGroupId AND ClientId = @ClientId AND PermissionId = @PermissionId
ELSE
INSERT INTO auth.UserPermissions (ClientId, UserGroupId, PermissionId)
VALUES (@ClientId, @UserGroupId, @PermissionId)";

_command.CommandText = _query;
_command.Parameters.AddWithValue("@UserGroupId", _obj.UserGroupId);
_command.Parameters.AddWithValue("@ClientId", clientId);
_command.Parameters.AddWithValue("@PermissionId", _obj.PermissionId);

await _command.ExecuteNonQueryAsync(token);
_command.Parameters.Clear();

1 个答案:

答案 0 :(得分:1)

您可以使用col = @param OR (col IS NULL AND @param IS NULL)

IF EXISTS(
 SELECT 1
 FROM auth.UserPermissions ur 
 WHERE (UserGroupId=@UserGroupId OR(UserGroupId IS NULL AND @UserGroupId IS NULL))
 AND(ClientId=@ClientId OR(ClientId IS NULL AND @ClientId IS NULL))
 AND(PermissionId=@PermissionId OR(PermissionId IS NULL AND @PermissionId IS NULL))
)
DELETE FROM auth.UserPermissions 
WHERE (UserGroupId=@UserGroupId OR (UserGroupId IS NULL AND @UserGroupId IS NULL))
 AND(ClientId=@ClientId OR (ClientId IS NULL AND @ClientId IS NULL))
 AND(PermissionId=@PermissionId OR(PermissionId IS NULL AND @PermissionId IS NULL));
ELSE
INSERT INTO auth.UserPermissions (ClientId, UserGroupId, PermissionId)
VALUES (@ClientId, @UserGroupId, @PermissionId);