What is better, dynamic SQL or where case?

可紊 提交于 2019-12-06 09:12:36

Generally it depends, but most often I use dynamic queries as a last resort. Regarding your question, I would most probably go with the CASE solution, but I think your CASE expressions are unnecessarily complicated. I would replace the WHERE clause with something like this:

...
WHERE
    TD1.columnTest1 = COALESCE(NULLIF(@var1, 0), TD1.columnTest1)
    AND   
    TD2.columnTest2 = COALESCE(NULLIF(@var2, 0), TD2.columnTest2)
    AND   
    TD1.columnTest3 = COALESCE(NULLIF(@var3, 0), TD1.columnTest3)

With proper indexing this shouldn't be too slow.

The dynamic query will lead to an index scan.

The case will lead to a seq scan (i.e. read the whole table).

So definitely go with the dynamic query.

Phil Murray

In my experience a dynamic where clause provides better performance. Especially over large datasets.

And a very good explanation is in Catch All Queries.

sam11

I have used the option "Andriy M" posted using coalesce and nullif functions.

But this option works only with the '=' operator, yet to find how to use it with other conditions, one example is using the 'IN' keyword.

TD1.columnTest1 = (
    CASE 
        WHEN (
            ( TD1.columnTest1 
                IN (
                    SELECT item FROM dbo.Splitfunction(@comaSepValues,',')
                )
            ) 
            OR 
            NULLIF(@PlaceTypeCode,'') IS NULL 
        ) THEN columnTest1
        ELSE NULL 
    END
)

Let me know if this works or not.

There are two ways to execute dynamic query 1. Exec 2. sp_executeSQL

if you want to reuse your execution plan, then go for sp_executeSQL option.

'SP_ExecuteSQL' accepts parameters, so you can directly pass your parameter to this query which will intern reuse your execution plan.

Dynamic queries are not always in bad performance specially when you are using it appropriately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!