【问题标题】:Select query on SQL where parameter1 OR parameter2在 SQL where parameter1 OR parameter2 上选择查询
【发布时间】:2014-10-20 18:19:20
【问题描述】:
CREATE PROCEDURE [dbo].[SPPeople]
(
   @Name varchar(50) = null,
   @Status1 char(1) = '0',
   @Status2 char(1) = '0',
   @Status3 char(1) = '0'
)
as
   SELECT 
      People.Name, People.Age 
   FROM 
      People
   WHERE
      (People.Name = CASE WHEN @Name is null THEN People.Name ELSE @Name END) 
      AND
      ((People.Status1 = CASE WHEN @Status1 = '0' THEN People.Status1 ELSE @Status1 END) 
       OR
       (People.Status2 = CASE WHEN @Status2 = '0' THEN People.Status2 ELSE @Status2 END)
       OR
       (People.Status3 = CASE WHEN @Status3 = '0' THEN People.Status3 ELSE @Status3 END))

如果参数@Status1@Status2 等于1,则查询应返回必须具有Status1Status2 等于1 的寄存器,而不依赖于Status3

但是当我将@Status1@Status2 作为1 传递时,上面的查询会返回所有寄存器。

【问题讨论】:

  • 这个查询是否执行?在最后一行(Status2 和 Status3 之间)之前似乎缺少布尔条件
  • 真的不见了。我添加了“或”以便它执行。

标签: sql sql-server stored-procedures parameters where


【解决方案1】:

尝试使用此逻辑:

SELECT p.Name, p.Age 
FROM People p
WHERE (@Name is null OR p.Name = @Name) AND
      (@status1 <> '0' and p.Status1 = @status1 or
       @status2 <> '0' and p.Status2 = @status2 or
       @status3 <> '0' and p.Status3 = @status3
      );

大多数人发现理解where 子句中的case 表达式比理解布尔逻辑更难。

【讨论】:

  • 这个逻辑中唯一的问题是,如果我传递所有状态等于 '0' 查询应该选择所有寄存器,而不是无。
  • @EduardoMoreira,您可以随时将 @Status1+@Status2+@Status3 = 0 OR ... 添加到 WHERE 子句中,并将其他所有内容放在另一组括号中。
【解决方案2】:

我认为您可以修改WHERE 条件以直接与参数进行比较

WHERE
People.Name = @Name 
AND 
(
People.Status1 = @Status1 
OR
People.Status2 = @Status2 
OR
People.Status3 = @Status3 
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多