选择具有多个参数化子句子的查询

时间:2013-03-25 18:34:10

标签: asp.net sql sql-server razor-2

我有一个包含2个下拉列表和3个复选框的表单,用户可以从中选择搜索数据库。由于所有表都很小,我想使用单个SELECT语句来返回结果。我在mikesdotnetting上找到了一个扩展,它适用于单个IN子句

using System;
using System.Collections.Generic;
using WebMatrix.Data;
using System.Linq;

public static class DatabaseExtensions
{
public static IEnumerable<dynamic> QueryIn(this Database db, string commandText, string values)
{
    if (string.IsNullOrEmpty(values))
        throw new ArgumentException("Value cannot be null or an empty string", "values");
    var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var temp2 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var temp3 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var parms = temp.Select((s, i) => "@" + i.ToString()).ToArray();
    var parms2 = temp2.Select((s, i) => "@" + i.ToString()).ToArray();
    var parms3 = temp3.Select((s, i) => "@" + i.ToString()).ToArray();
    var inclause = string.Join(",", parms, parms2, parms3);
    return db.Query(string.Format(commandText, inclause), temp, temp2, temp3);
}

public static int ExecuteIn(this Database db, string commandText, string values)
{
    if (string.IsNullOrEmpty(values))
        throw new ArgumentException("Value cannot be null or an empty string", "values");
    var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var parms = temp.Select((s, i) => "@" + i.ToString()).ToArray();
    var inclause = string.Join(",", parms);
    return db.Execute(string.Format(commandText, inclause), temp);
}
 }

以下是显示我如何设想查询的页面代码:

var gender = Request["genderSvd"];
var person = Request["chkPerson"];
var spec = Request["chkSpec"];
var county = Request["ctyLoc"];
var crim = Request["chkCrim"];

    var db = Database.Open("HBDatabase");
    var sql = "SELECT DISTINCT tblProgram.* FROM lnkPrgPersonSvd INNER JOIN tblProgram ON lnkPrgPersonSvd.prgId = tblProgram.prgId";
    sql += "INNER JOIN lnkPrgSpecial ON tblProgram.prgId = lnkPrgSpecial.prgId INNER JOIN tblProgram.prgId = lnkPrgCriminal.prgId ";
    sql += "WHERE (lnkPrgPersonSvd.personId IN ({0})) AND (lnkPrgSpecial.specId IN ({1})) AND tblProgram.prgGenderSvdId = @2 ";
    sql += "AND tblProgram.prgCounty = @3 AND (lnkPrgCriminal.criminalId IN ({4}))";

    var prgList = db.QueryIn(sql, person, spec, gender, county, crim);
显然,这不起作用,因为扩展名不能占用那么多参数。我正在寻找一种方法来修改类以允许其他参数,以便查询可以只运行一次。这可能是不可能的。

另外,我确实找到了几个处理单个参数化in子句的线程,但没有真正提到带变量列表的倍数。

我不擅长存储过程或编写自己的类。有什么建议吗?

0 个答案:

没有答案