Is there a standard approach to generating sql dynamically?

后端 未结 8 2219
滥情空心
滥情空心 2021-02-20 00:17

I want to ask how other programmers are producing Dynamic SQL strings for execution as the CommandText of a SQLCommand object.

I am producing parameterized queries conta

8条回答
  •  时光说笑
    2021-02-20 00:59

    If you really need to do this from code, then an ORM is probably the way to go to try to keep it clean.

    But I'd like to offer an alternative that works well and could avoid the performance problems that accompany dynamic queries, due to changing SQL that requires new query plans to be created, with different demands on indexes.

    Create a stored procedure that accepts all possible parameters, and then use something like this in the where clause:

    where...
    and (@MyParam5 is null or @MyParam5 = Col5)
    

    then, from code, it's much simpler to set the parameter value to DBNull.Value when it is not applicable, rather than changing the SQL string you generate.

    Your DBAs will be much happier with you, because they will have one place to go for query tuning, the SQL will be easy to read, and they won't have to dig through profiler traces to find the many different queries being generated by your code.

提交回复
热议问题