Is there a standard approach to generating sql dynamically?

后端 未结 8 2378
滥情空心
滥情空心 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 01:05

    We created our own FilterCriteria object that is kind of a black-box dynamic query builder. It has collection properties for SelectClause, WhereClause, GroupByClause and OrderByClause. It also contains a properties for CommandText, CommandType, and MaximumRecords.

    We then jut pass our FilterCriteria object to our data logic and it executes it against the database server and passes parameter values to a stored procedure that executes the dynamic code.

    Works well for us ... and keeps the SQL generation nicely contained in an object.

    0 讨论(0)
  • 2021-02-20 01:06

    ORMs have already solved the problem of dynamic SQL generation (I prefer NHibernate/ActiveRecord). Using these tools you can create a query with an unknown number of conditions by looping across user input and generating an array of Expression objects. Then execute the built-in query methods with that custom expression set.

    List<Expression> expressions = new List<Expression>(userConditions.Count);
    foreach(Condition c in userConditions)
    {
        expressions.Add(Expression.Eq(c.Field, c.Value));
    }
    SomeTable[] records = SomeTable.Find(expressions);
    

    There are more 'Expression' options: non-equality, greater/less than, null/not-null, etc. The 'Condition' type I just made up, you can probably stuff your user input into a useful class.

    0 讨论(0)
提交回复
热议问题