Sql Templating

Adam Schroder edited this page Dec 5, 2013 · 3 revisions

You can use the SqlBuilder to build queries up with conditional wheres, columns, orderby's etc.

var sqlBuilder = new SqlBuilder();
var template = sqlBuilder.AddTemplate("select * from users where age > @0 and /**where**/", 10);

Here you can specify one of Where, Select, Join, LeftJoin, OrderBy, OrderByCols, GroupBy and Having The corresponding sql tokens are specified below.

    /// Adds a filter. The Where keyword still needs to be specified. Uses /**where**/
    public SqlBuilder Where(string sql, params object[] parameters)

    /// Replaces the Select columns. Uses /**select**/
    public SqlBuilder Select(params string[] columns)

    /// Adds an Inner Join. Uses /**join**/
    public SqlBuilder Join(string sql, params object[] parameters)

    /// Adds a Left Join. Uses /**leftjoin**/
    public SqlBuilder LeftJoin(string sql, params object[] parameters)

    /// Adds an Order By clause. Uses /**orderby**/
    public SqlBuilder OrderBy(string sql, params object[] parameters)

    /// Adds columns in the Order By clause. Uses /**orderbycols**/
    public SqlBuilder OrderByCols(params string[] columns)

    /// Adds a Group By clause. Uses /**groupby**/
    public SqlBuilder GroupBy(string sql, params object[] parameters)

    /// Adds a Having clause. Uses /**having**/
    public SqlBuilder Having(string sql, params object[] parameters)

The statements can be chained and the parameters start from 0 for each new statement.

sqlBuilder
    .Where("height >= @0", 176)
    .Where("weight > @0 and weight < @1", 30, 60);

var db = new Database("conn");
db.Fetch<User>(template);

The templates can be used anywhere the Sql class can be used.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.