如何编写具有嵌套过滤器的SQL查询。
信息:2个搜索过滤器
第一个过滤器:Id,Name,Date
第二个过滤器:取决于第一个,对于Id:精确,范围; for name:exact,like;对于日期:确切,范围。
在LINQ代码中,它的完成类似于:
theList = somelistFromDb;
case filter1
case "Id"
if filter2 == "exact"
theList.where(x => x == searchkey);
else if filter 2 == "range"
theList.where(x => x >= searchkey && x<=searchkey2);
case "Name"
if filter2 == "exact"
theList.where(x => x == searchkey);
else if filter2 == "like"
theList.where(x => x.contains("searchkey));
...
如何将上述LINQ Pseudocode转换为SQL?
答案 0 :(得分:1)
SELECT
...
WHERE
(:filterParam='Id' AND <all the Id filter conditions> here)
OR
(:filterParam='Name' AND <all the Name filter conditions> here)
答案 1 :(得分:1)
select * from [Table] where
((@filter1='Id') and
((filter2='exact' and [Table].[Id]=@searchkey) OR
(filter2='range' and [Table].[Id]>=@searchkey and [Table].[Id]<=@searchkey2) ))
OR
((@filter1='Name') and
.....
答案 2 :(得分:1)
编写一个满足或排除所有条件的TSQL查询通常非常不理想 - 这会导致糟糕的查询计划。试图在TSQL中做所有的想法是......有点难看 - TSQL根本不是一个很好的语言。
所以:我通常这样做的方法是在C#中构建查询,例如:
static void AppendFilter(StringBuilder filter, string clause)
{
filter.Append(filter.Length == 0 ? " where " : " and ").Append(clause);
}
StringBuilder filter = new StringBuilder();
if(/* some condition */)
AppendFilter(filter, "row.Foo = @foo");
if(/* some condition */)
AppendFilter(filter, "row.Bar > @bar");
// ...
string tsql = "select * from SomeTable row" + filter.ToString();
// pack params, exec
此:
就个人而言,我也使用dapper来执行,因为它具有内置的(基本)参数分析,允许简单:
var rows = conn.Query<SomeType>(tsql, new { foo, bar, ... }).ToList();
(但它仍然只发送必要的参数)
另一种方法是在每个if
中添加参数。