Parameterizing a ServiceStack custom SQL query

て烟熏妆下的殇ゞ 提交于 2019-12-12 22:55:36

问题


I have the following custom SQL Query with OrmLite:

var results = db.Select<Tuple<Customer,Purchase>>(@"SELECT c.*, 0 EOT, p1.*
    FROM customer c
    JOIN purchase p1 ON (c.id = p1.customer_id)
    LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
        (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
    WHERE p2.id IS NULL;");

What is the best way to add an optional WHERE clauses to, for instance, filter a given customer name field when the field has a value or to add pagination to the query?


回答1:


If you're working with Custom SQL you just need to construct the additional queries yourself, e.g:

var sql = @"SELECT c.*, 0 EOT, p1.*
    FROM customer c
    JOIN purchase p1 ON (c.id = p1.customer_id)
    LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
        (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
    WHERE p2.id IS NULL";

//string name = "Customer Name";
string name = null;
if (name != null)
{
    sql += "\nAND name = @name";
}

int? limit = 100;
if (limit != null)
{
    sql += $"\nLIMIT {limit}";
}

var results = db.Select<Tuple<Customer,Purchase>>(sql, new { name });

A Live Example of this is available on Gistlyn.



来源:https://stackoverflow.com/questions/43244785/parameterizing-a-servicestack-custom-sql-query

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