Is there a standard approach to generating sql dynamically?

后端 未结 8 2335
滥情空心
滥情空心 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:53

    I had the need to do this on one of my recent projects. Here is the scheme that I am using for generating the SQL:

    • Each component of the query is represented by an Object (which in my case is a Linq-to-Sql entity that maps to a table in the DB). So I have the following classes: Query, SelectColumn, Join, WhereCondition, Sort, GroupBy. Each of these classes contains all details relating to that component of the query.
    • The last five classes are all related to a Query object. So the Query object itself has collections of each class.
    • Each class has a method that can generate the SQL for the part of the query that it represents. So creating the overall query ends up calling Query.GenerateQuery() which in turn enumerates through all of the sub-collections and calls their respective GenerateQuery() methods

    It is still a bit complicated, but in the end you know where the SQL generation for each individual part of the query originates (and I don't think that there are any big switch statements). And don't forget to use StringBuilder.

提交回复
热议问题