需要根据变量是否为空来从表中选择记录。如果为null,则检查不等于条件

时间:2013-11-14 10:59:42

标签: sql sql-server

对于那些每天在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'

2 个答案:

答案 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)

尽量不要在同一上下文中混用ANDOR

您错过了状态条件的全局括号:

而不是

(@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