对于那些每天在sql上工作的人来说,这听起来很容易。 如果value为null,我需要根据变量值选择记录 status列不等于3,变量值不等于基于变量值的null过滤器。
DECLARE @status int
set @status = 1
SELECT change_set_history_id, files_changed, is_previewed
FROM dbo.ChangeSetHistory WITH (NOLOCK)
WHERE [user_name] = 'djacob' AND
[culture] = 'nl-NL' AND
(@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status) AND
[approver] = null AND
is_deleted = 0
如果尝试使用此部件查询,则可以正常工作 DECLARE @status int 设置@status = 1 从ChangeSetHistory中选择*,其中status = @status和user_name ='djacob'和culture ='nl-NL'
答案 0 :(得分:1)
用另一对括号括起OR
条件:
SELECT change_set_history_id, files_changed, is_previewed
FROM dbo.ChangeSetHistory WITH (NOLOCK)
WHERE [user_name] = 'djacob' AND
[culture] = 'nl-NL' AND
((@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status)) AND
[approver] IS null AND
is_deleted = 0
如果您的条件等同于:
WHERE ([user_name] = 'djacob' AND [culture] = 'nl-NL' AND (@status IS NULL AND [status] <> 3)) OR
((@status IS NOT NULL AND [status] = @status) AND [approver] = null AND is_deleted = 0)
测试用例:
DECLARE @status int
SET @status = 1
SELECT *
FROM (
SELECT NULL [status] UNION ALL
SELECT 1 [status] UNION ALL
SELECT 2 [status] UNION ALL
SELECT 3 [status]
) T
WHERE ((@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status));
我看到的其他问题是[approver] = null
条件。它应该是[approver] is null
答案 1 :(得分:0)
尽量不要在同一上下文中混用AND
和OR
。
您错过了状态条件的全局括号:
而不是
(@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status)
一定是
((@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status))
它应该可以解决您的问题:
DECLARE @status int
set @status = 1
SELECT change_set_history_id, files_changed, is_previewed
FROM dbo.ChangeSetHistory WITH (NOLOCK)
WHERE [user_name] = 'djacob' AND
[culture] = 'nl-NL' AND
((@status IS NULL AND [status] <> 3) OR (@status IS NOT NULL AND [status] = @status)) AND
[approver] = null AND
is_deleted = 0