简体   繁体   中英

SQL Where statement with CASE variable

Im sorry I do not have a complete query because my original is actually very long but I feel you may be able to spot where I have an error in my syntax. Basically I declare 2 variables and if one variable is blank I need the where statement to be where the field is not in the other variable.

Where dnCP_FromServiceDate >= '01/01/2016' And
dnCP_FromServiceDate <= '01/31/2016' And
dnCP_RecordStatus <> 'V' 
AND CASE  WHEN @inpDXIN = ''  THEN
predxDiagnosisCode not in (@inpDXNOTIN)
ELSE  predxDiagnosisCode IN (@inpDXIN)
END 

Even if I could get a snippet of a query using a similar statement i can figure mine out but i cant find anything similar. Any help is greatly appreciated

In general, you don't want to use case in a where clause. Instead, just use regular boolean logic:

Where dnCP_FromServiceDate >= '2016-01-01' and
      dnCP_FromServiceDate <= '2016-01-31' and
      dnCP_RecordStatus <> 'V' and
      ( (@inpDXIN = '' and predxDiagnosisCode <> @inpDXNOTIN) or
        (@inpDXIN <> '' and  predxDiagnosisCode IN (@inpDXIN)
     )

Notes:

  • Use ISO/ANSI standard date formats. Much less ambiguous.
  • IN (@var) is the same as = @var . You cannot pass an in list through a variable. If you need that functionality, then ask another question.
  • Most dialects of SQL do not allow boolean expressions to be returned from a case . The above gets around this "limitation".

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