sql where子句仅在包含时才包含

时间:2011-11-28 03:41:22

标签: sql case where

我想知道是否可以为多个客户端运行脚本,我可以在运行指定客户端时添加额外的where子句,而不必多次重写基本脚本?

EG。基本脚本是

SELECT Status, count(distinct T1.AccountNo)
FROM Orders (nolock), Accounts (NOLOCK)
WHERE Orders.AccountNo = Accounts .AccountNo  
AND date between '1 Oct 2011' and '31 Oct 2011'
GROUP BY Status

但是当我为客户A竞选时,我想要包含额外的标准

AND Accounts.Role IN ('User','Admin')
AND Accounts.Active= 'Y'

3 个答案:

答案 0 :(得分:2)

SELECT Status, count(distinct T1.AccountNo)
FROM Orders (nolock), Accounts (NOLOCK)
WHERE Orders.AccountNo = Accounts .AccountNo  
AND date between '1 Oct 2011' and '31 Oct 2011'
AND CASE WHEN Client = 'A' THEN Accounts.Role ELSE 'User' END IN ('User', 'Admin')
AND CASE WHEN Client = 'A' THEN Accounts.Active ELSE 'Y' END = 'Y'
GROUP BY Status

答案 1 :(得分:1)

在SQL Server上,您可以按如下方式使用HOST_NAME():

SELECT Status, count(distinct T1.AccountNo)
FROM Orders (nolock), Accounts (NOLOCK)
WHERE Orders.AccountNo = Accounts .AccountNo  
AND date between '1 Oct 2011' and '31 Oct 2011'
AND ((HOST_NAME() <> 'ClientA') OR (Accounts.Role IN ('User') AND Accounts.Active= 'Y'))
GROUP BY Status

答案 2 :(得分:0)

当不需要参数时,您会在存储过程中看到这一点:

SELECT *
FROM SomeTable
WHERE ((@myvariable IS NULL OR @myvariable = mycolumn))

不幸的是,这通常会导致扫描,因为它可能会或可能不会短路。

我要发布的另一个例子与Derek Kromm的相同。

最后你可以使用Dynamic SQL - 人们要么喜欢它,要么讨厌它。