简体   繁体   English

带CASE变量的SQL Where语句

[英]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. 基本上,我声明2个变量,如果一个变量为空,则需要where语句将字段不在另一个变量中。

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. 通常,您不想在where子句中使用case 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. 使用ISO / ANSI标准日期格式。 Much less ambiguous. 少含糊。
  • IN (@var) is the same as = @var . IN (@var)= @var相同。 You cannot pass an in list through a variable. 您不能通过变量传递in列表。 If you need that functionality, then ask another question. 如果您需要该功能,请询问另一个问题。
  • Most dialects of SQL do not allow boolean expressions to be returned from a case . SQL的大多数方言不允许从case返回布尔表达式。 The above gets around this "limitation". 上面绕过了这个“局限性”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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