C# 如何设置sql查询的可选参数?

C# 如何设置sql查询的可选参数?,c#,asp.net,sql,web-services,sql-server-2008,C#,Asp.net,Sql,Web Services,Sql Server 2008,我在ASP.Net中构建了一个Web服务,它向我发送一个房间列表 参数是由逗号分隔的id 我将它们保存为一个字符串,并构建了一个sql select查询 当我发送所有4个参数时,我发现一切正常,我得到了一个结果。但是当我发送少于4次时,我会得到一个错误 System.Data.SqlClient.SqlException: Incorrect syntax near ')'. 如何在sql查询中设置可选参数以仅选择输入的值 以下是我目前的代码: internal static List<

我在ASP.Net中构建了一个Web服务,它向我发送一个房间列表

参数是由逗号分隔的id

我将它们保存为一个字符串,并构建了一个sql select查询

当我发送所有4个参数时,我发现一切正常,我得到了一个结果。但是当我发送少于4次时,我会得到一个错误

System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
如何在sql查询中设置可选参数以仅选择输入的值

以下是我目前的代码:

internal static List<RAUM> Raum(string RAUMKLASSE_ID, string STADT_ID, string GEBAEUDE_ID, string REGION_ID)
{
    List<RAUM> strasseObject = new List<RAUM>();
    string raumklasseid = RAUMKLASSE_ID;
    string gebaudeid = GEBAEUDE_ID;
    string stadtid = STADT_ID;
    string regionid = REGION_ID;

    using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
    using (SqlCommand cmd = new SqlCommand(@"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r WHERE RAUMKLASSE_ID IN (" + raumklasseid + ") AND STADT_ID IN (" + stadtid + ") AND GEBAEUDE_ID IN (" + gebaudeid + ") AND REGION_ID IN (" + regionid + ")", con))
    {
        con.Open();

        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                if (rdr["BEZEICHNUNG"] != DBNull.Value && rdr["ID"] != DBNull.Value)
                {
                    strasseObject.Add(new RAUM()
                    {
                        RaumName = rdr["BEZEICHNUNG"].ToString(),
                        RaumID = rdr["ID"].ToString()
                    });
                }
            }
        }
    }

    return strasseObject;
}
内部静态列表Raum(字符串RAUMKLASSE\u ID、字符串statt\u ID、字符串GEBAEUDE\u ID、字符串REGION\u ID)
{
List strasseObject=新列表();
字符串raumklasseid=RAUMKLASSE\u ID;
字符串gebaudeid=GEBAEUDE_ID;
字符串stadtid=STADT_ID;
字符串regionid=区域\单元ID;
使用(SqlConnection con=newsqlconnection(@“数据源=Localhost\SQLEXPRESS;初始目录=BOOK-IT-V2;集成安全性=true;”)
使用(SqlCommand cmd=new SqlCommand(@“选择r.bezeichung作为bezeichung,选择r.ID作为RAUM r的ID,其中RAUMKLASSE_ID在(“+raumklasseid+”)中,statt_ID在(“+statid+”)中,gebaueude_ID在(“+gebaudeid+”)中,regionid在(“+regionid+”)中,con))
{
con.Open();
使用(SqlDataReader rdr=cmd.ExecuteReader())
{
while(rdr.Read())
{
if(rdr[“BEZEICHNUNG”!=DBNull.Value&&rdr[“ID”!=DBNull.Value)
{
添加(新的RAUM()
{
RaumName=rdr[“Bezeichung”].ToString(),
RaumID=rdr[“ID”].ToString()
});
}
}
}
}
返回对象;
}

提前感谢您的帮助。

编写存储过程并传递参数总是一种更好的方法。但是在您的方法中,您应该分割查询,因为不确定值。所以,你的代码应该是这样的

你自己测试一下,我没有检查

string raumklasseid = RAUMKLASSE_ID;
        string gebaudeid = GEBAEUDE_ID;
        string stadtid = STADT_ID;
        string regionid = REGION_ID;
        string whereClause = string.Empty;

if (!string.IsNullorEmpty(raumklasseid))
{
   whereClause = "RAUMKLASSE_ID IN (" + raumklasseid + ")";
}
if (!string.IsNullorEmpty(stadtid ))
{
   if(string.IsNullorEmpty(whereClause)
      whereClause = "STADT_ID IN (" + stadtid + ")";
   else 
      whereClause += "AND RSTADT_ID IN (" + stadtid + ")";
}
if (!string.IsNullorEmpty(stadtid ))
{
   if(string.IsNullorEmpty(whereClause)
      whereClause = "STADT_ID IN (" + stadtid + ")";
   else 
      whereClause += "AND RSTADT_ID IN (" + stadtid + ")";
}
if (!string.IsNullorEmpty(regionid))
{
   if(string.IsNullorEmpty(whereClause)
      whereClause = "REGION_ID IN (" + regionid + ")";
   else 
      whereClause += "AND REGION_ID IN (" + regionid + ")";
}

if(!string.IsNullorEmpty(whereClause)
whereClause = "WHERE " + whereClause ;

// now your cmd should be like that

using (SqlCommand cmd = new SqlCommand(@"SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r " + whereClause , con))

假设参数
REGION\u ID
是一个空字符串。查询的这一部分类似于:

...AND REGION_ID IN ()...
因为在
和REGION\u ID in(“+regionid+”)
中,
regionid
变量将被替换为空字符串。这不是有效的SQL语法,因此会出现该异常

声明如下所示的函数:

private static void AppendConstrain(StringBuilder query, string name, string value)
{
    if (String.IsNullOrWhiteSpace(value))
        return;

    if (query.Length > 0)
        query.Append(" AND ");

    query.AppendFormat("{0} IN ({1})", name, value);
}
然后更改代码,以以下方式生成查询:

StringBuilder constrains = new StringBuilder();
AppendConstrain(contrains, "RAUMKLASSE_ID", RAUMKLASSE_ID);
AppendConstrain(contrains, "GEBAEUDE_ID", GEBAEUDE_ID);
AppendConstrain(contrains, "STADT_ID", STADT_ID);
AppendConstrain(contrains, "REGION_ID", REGION_ID);

StringBuilder query =
    new StringBuilder("SELECT r.BEZEICHNUNG AS BEZEICHNUNG, r.ID AS ID FROM RAUM r");

if (constrains.Length > 0)
{
    query.Append(" WHERE ");
    query.Append(constrains);
}

using (SqlCommand cmd = new SqlCommand(query.ToString(), con))
{
    // Your code...
}

转储您的查询,例如,您可能有以下内容:“…来自RAUM r,其中RAUMKLASSE_ID IN()。。。“这是无效的。只有当参数有值时,才应该附加每个约束。我不知道你的意思。您能详细解释一下吗?我添加了一个带有代码的答案。如果问题得到解决,请将一个答案标记为已接受谢谢我尝试了您的代码,但仍然收到相同的错误。我不知道why@ErayGeveci记录query.ToString()并在此处发布。我不知道如何记录服务器上的Web服务。我会寻找解决办法,然后写信给你results@ErayGeveci您可以使用System.Diagnostics.EventLog。对于此测试,您甚至可以…将查询本身作为消息抛出异常!但是,当我在文件夹中公开项目并手动将其复制到服务器时,我无法使用它。我无法在visual studio中测试它,因为数据库仅存在于服务器上