简体   繁体   中英

SQL CASE statement for boolean values

I have the following SQL stored procedure

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

My problem is that isArchived is of type bit in the table, and on a web page I have a dropdownlist with three values for isArchived: ALL, Yes, No.

For Yes it is 1 (true), for No it is 0 (false) but not sure what to put in for this line: WHEN @isArchived = 'ALL' THEN ??? ideally it would totally ignore the line AND [isArchived] = @isArchived but not sure what the syntax for that is.

If you would like to avoid filtering when @isArchived = 'ALL' , you can compare [isArchived] to itself (as long as the value can't be 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)

Note that this kind of conditional filtering can impact your execution plans, so you might want to investigate a different approach as discussed in this article:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM