0

对于每天在 sql 上工作的人来说,这听起来很容易,这些人占用了我很多时间。我有一个表,如果值为空,则我需要根据变量值选择记录,将状态列设置为不等于 3,变量值不等于基于变量值的空过滤器..

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 set @status = 1 select * from ChangeSetHistory where status = @status and user_name = 'djacob' andculture = 'nl-NL'

4

2 回答 2

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

于 2013-11-14T11:21:49.477 回答
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
于 2013-11-14T11:21:25.707 回答