views:

57

answers:

1

I am converting a stored procedure which I had previously written as a string then, using BIT parameters I decided whether to append certain WHERE/ON clauses

This sp is passed a number of comma-separated strings and then some of the dynamic WHERE clauses are like:

IF @pUse_Clause_A THEN SET @WhereClause = @WhereClause + ' AND [FIELD_A] IN (' + @pComma_Separated_List_A + ')'

In this case, @pComma_Separated_List_A is something like '1,3,6,66,22' ... a list of the things I want included.

Now I am changing these from strings into TVP,s so I can just use "real" SQL like AND [FIELD_A] IN (SELECT [TVP_FIELD] FROM @pTVP_A)

When I do this, I don't like the string-building method

However, I also don't like having to nest the IF statements.

IF A 
    ENTIRE SQL WHERE A
ELSE
    ENTIRE SQL WITHOUT WHERE CLAUSE

The more parameters I add, the more complicated it gets:

IF A
    IF B
        SQL WHERE A AND B
    ELSE
        SQL WHERE A
ELSE
    IF B
        SQL WHERE B
    ELSE
        SQL

What I would rather do is something like this:

SELECT * FROM TABLE
WHERE 1=1
CASE USE_A WHEN 1 THEN 
     AND [FIELD_A] IN (SELECT A FROM TBP_A)
END
CASE USE_B WHEN 1 THEN
     AND [FIELD_B] IN (SELECT B FROM TVP_B)
END

I know it ignored SQL outside the chosen "IF" result, but having all that duplicated statement seems sloppy

+1  A: 

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

KM
I have read both of those before, but thank you for the links (I hope they will be useful to other readers!)In this case the query itself is well optimized. It seems like I have no choice but to nest the IF statements and repeat the query. I was hoping I could use a CASE (or something similar) to "turn on" a WHERE clause instead of using a varchar and then calling EXEC()The "string-builder" method doesn't play nice with TVP
Matthew PK