我必须根据行是否存在来删除或插入。但是其中一列可能是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: NULL
和Col 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();
答案 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);