[英]SQL Server Case in Where clause
I am trying to create a stored proc and have a where clause where to different operations can take place depending on the value of a parameter passed in: 我正在尝试创建一个存储的proc并有一个where子句,根据传入的参数值,可以在何处进行不同的操作:
WHERE
(cdr.CircuitReference = @CircuitReference)
AND
CASE WHEN (@JDEDocumentReference <> 'Unbilled Calls')
THEN
sct.JDEDocumentReference = @JDEDocumentReference
ELSE
((sct.JDEDocumentReference IS NULL) AND (sc.StartDate IS NOT null AND ((sc.CloseDate IS null) OR (datediff(day,sc.CloseDate,getdate()) < 0)) AND stp.SipTrunksProduct = sct.ProductCode))
END
I've just posted my where clause above but when i try to execute the script i get the following error: 我刚刚在上面发布了我的where子句,但是当我尝试执行脚本时,出现以下错误:
Incorrect syntax near '='.
Is this the correct way to do a conditional statement in a where clause of an sql query? 这是在sql查询的where子句中执行条件语句的正确方法吗?
Thanks 谢谢
STATEMENT FULLY WRONG : There is no need for case here(Even there is a possibility to it correctly. But here no needed). 完全错误的陈述:这里不需要案例(即使有可能正确,但是这里也不需要)。
USE: 采用:
(cdr.CircuitReference = @CircuitReference)
AND ((JDEDocumentReference <> 'Unbilled Calls'
AND @JDEDocumentReference) OR @JDEDocumentReference = 'Unbilled Calls' )
OR (JDEDocumentReference = 'Unbilled Calls'
AND ((sct.JDEDocumentReference IS NULL) AND (sc.StartDate IS NOT null AND ((sc.CloseDate IS null)
OR (datediff(day,sc.CloseDate,getdate()) < 0)) AND stp.SipTrunksProduct = sct.ProductCode)))
This problem could be solved without a CASE statement by using the following: 使用以下命令,无需CASE语句即可解决此问题:
WHERE
(cdr.CircuitReference = @CircuitReference)
AND
((@JDEDocumentReference <> 'Unbilled Calls' AND sct.JDEDocumentReference = @JDEDocumentReference)
OR
(@JDEDocumentReference = 'Unbilled Calls' AND ((sct.JDEDocumentReference IS NULL) AND (sc.StartDate IS NOT null AND ((sc.CloseDate IS null) OR (datediff(day,sc.CloseDate,getdate()) < 0)) AND stp.SipTrunksProduct = sct.ProductCode))))
You can use something like this, 你可以这样使用
WHERE
(cdr.CircuitReference = @CircuitReference)
AND sct.JDEDocumentReference = case when @JDEDocumentReference <> 'Unbilled Calls' Then @JDEDocumentReference end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.