SQL with子句dynamic where参数

时间:2012-10-23 15:44:09

标签: sql sql-server tsql

`SELECT * FROM [case]
WHERE status  = '0'
and date_rec > '01 January 2012'
and 'ClientFilter' = 
CASE @clientcode 
    WHEN '' THEN 'ClientFilter' 
    ELSE
CASE WHEN client in 
(SELECT ID COLLATE DATABASE_DEFAULT FROM
GREEN.dbo.fnSplitter(@clientcode)) THEN 'ClientFilter' END  END; `

我想在上面的查询中添加一个额外的过滤器,类似于clientfilter。有谁知道如何做到这一点。例如,如下所示,但不起作用。

`SELECT * FROM [case]
WHERE status  = '0'
and date_rec > '01 January 2012'
and 'ClientFilter' = 
CASE @clientcode 
    WHEN '' THEN 'ClientFilter' 
    ELSE
CASE WHEN client in 
(SELECT ID COLLATE DATABASE_DEFAULT FROM GREEN.dbo.fnSplitter (@clientcode))
THEN 'ClientFilter' END  END;
and 'SchemeFilter' = 
CASE @schemecode  WHEN '' THEN 'SchemeFilter' 
ELSE
CASE WHEN client in 
(SELECT ID COLLATE DATABASE_DEFAULT FROM GREEN.dbo.fnSplitter(@schemecode))
THEN 'SchemeFilter' END  END; `

1 个答案:

答案 0 :(得分:1)

我找到了解决办法 这样,可以应用大量条件过滤器:

SELECT * FROM [case]
WHERE status  = '0'
AND date_rec > '01 January 2012'
AND 'SchemeFilter' = 
CASE @schemecode 
    WHEN '' THEN 'SchemeFilter' 
    ELSE
    CASE WHEN scheme in (SELECT ID COLLATE DATABASE_DEFAULT FROM GREEN.dbo.fnSplitter  (@schemecode)) THEN 'SchemeFilter' END  END
AND 'ClientFilter' = 
CASE @clientcode 
    WHEN '' THEN 'ClientFilter' 
    ELSE
    CASE WHEN client in (SELECT ID COLLATE DATABASE_DEFAULT FROM GREEN.dbo.fnSplitter(@clientcode)) THEN 'ClientFilter' END  END
AND 'Holderfilter' = 
CASE @holdercode
    WHEN '' THEN 'Holderfilter' 
    ELSE
    CASE WHEN holder in (SELECT ID COLLATE DATABASE_DEFAULT FROM GREEN.dbo.fnSplitter (@holdercode)) THEN 'Holderfilter' END  END
AND 'Officefilter' = 
CASE @officecode
    WHEN '' THEN 'Officefilter' 
    ELSE
    CASE WHEN [current] in (SELECT ID COLLATE DATABASE_DEFAULT FROM  GREEN.dbo.fnSplitter(@officecode)) THEN 'Officefilter' END  END