简体   繁体   中英

Case statement in where clause using not like and is not null

I'm pulling data from an existing table using a stored procedure that has some yes or no choices that the user picks on the front end through a checkbox. I want to limit writing a bunch of different If statements for every choice they make.

This portion of my where clause works. Data is either Y or N for this column.

Where... and IsSigned = Case When @IncludeSigned = 'Y' then IsSigned else 'N' end

I would like to add to the where using is not null and not like if this is possible between the square brackets. So far I have

and SignatureType = case when @IncludeElectronic = 'Y' then Type else [NOT like electronic] end

also

and ReviewDate = Case When @HasReviewDate = 'Y' then [ReviewDate is not null] else null end

This may help you use AND/OR instead of case

where (ReviewDate is not null or @HasReviewDate = 'Y' ) And (....)

ie when @HasReviewDate = 'Y' query will return the records with ReviewDate is not null and when @HasReviewDate != 'Y' then query will return the records with ReviewDate is null

think of it this way:-

Your first case statement has two possible results:-

IsSigned = 'Y'
IsSigned = 'N'

Your subsequent ones have problems as they don't make sense syntactically. So the second one as written returns

SignatureType = Type
SignatureType = [NOT like electronic]

and your third:

ReviewDate = [ReviewDate is not null]
ReviewDate = null end

SO the operator has to be before the case statement and apply to all of the results of the case statement.

For example

WHERE myfield not like CASE WHEN thatfield=1 THEN 'Fish' ELSE 'Chips END

would produce either

myfield not like 'Fish'

myfield not like 'Chips'

我相信您不能以这种方式使用,此外,您的查询内部可能会受到很大的影响,我的建议是改变您使用的策略。

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