开发者

Better way of performing dynamic conditional searching in TSQL?

We have a large-ish query here that has 开发者_StackOverflow中文版several params, and for each one, the query only differs by one portion of the where clause, like so:

CASE WHEN @IncludeNames = 1 AND @NameFilter IS NULL THEN

(SELECT blah FROM blahBlah

    INNER JOIN ... 
    INNER JOIN ...
    INNER JOIN ...
    WHERE blahBlah.Id = x.Id)

WHEN @IncludeNames = 1 AND @NameFilter IS NOT NULL THEN

(SELECT blah FROM blahBlah

    INNER JOIN ... 
    INNER JOIN ...
    INNER JOIN ...
    WHERE blahBlah.Id = x.Id
    AND table2.Id = @NameFilter

It goes on like that for several instances, differing only by one condition on the where clause.

Keep in mind this is in the middle of a larger select.

Is there a good way of cleaning this up, without placing it all into one large concatenated sql string and running exec on it, or using something absurd like multiple stored procs per block, as shown here: http://www.developerfusion.com/article/7305/dynamic-search-conditions-in-tsql/7/

Server is SQL Server 2008 R2. TIA!


Try setting up your query with an option of all or specific values for each clause e.g.

SELECT x.*
FROM   x
WHERE  (x.id = @NameFilter
OR     @NameFilter is null)
AND    (x.typeId = @typeFilter
OR     -1 =  @typeFilter)
AND    (x.date = @date
OR     @date is null)
AND    (x.someStingType = @someStringType
Or     '' = @someStringType)

This should allow you to concatenate your clauses into a single select statement. Each parameter may apply a filter or have no effect (if set to the default such as null, empty string or -1).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜