布尔值的SQL CASE语句

时间:2014-01-28 16:55:50

标签: sql sql-server-2008 stored-procedures

我有以下SQL存储过程

@Text varchar(max),
@isArchived varchar(10)

SELECT *
  FROM [Table1] 
  WHERE [StringText] = @ AND [isArchived] = 

  (CASE 
        WHEN @isArchived = 'ALL' THEN ???
        WHEN @isArchived = 'Yes' THEN 1
        WHEN @isArchived = 'No' THEN  0
    END)

我的问题是isArchived是表中的bit类型,在网页上我有一个下拉列表,其中包含三个isArchived值:ALL,Yes,No。

对于Yes,它是1(真),对于No,它是0(错误)但不确定要为此行添加什么:WHEN @isArchived = 'ALL' THEN ???理想情况下它会完全忽略行AND [isArchived] = @isArchived,但不确定它的语法是什么。

1 个答案:

答案 0 :(得分:2)

如果您希望在@isArchived = 'ALL'时避免过滤,可以将[isArchived]与自身进行比较(只要该值不能为NULL):

SELECT *
FROM [Table1] 
WHERE [StringText] = @Text AND [isArchived] = (
  CASE 
    WHEN @isArchived = 'ALL' THEN [isArchived]
    WHEN @isArchived = 'Yes' THEN 1
    WHEN @isArchived = 'No' THEN  0
  END)

请注意,这种条件过滤会影响您的执行计划,因此您可能希望调查本文中讨论的其他方法:

http://www.sommarskog.se/dyn-search-2008.html