数据库
首页 > 数据库> > 将C#字符串作为SELECT WHERE IN的SQL参数传递

将C#字符串作为SELECT WHERE IN的SQL参数传递

作者:互联网

我正在编写一个函数,以从列表框中选取尽可能多的多个选定项,然后从另一个表中选择过滤后的值,然后将vaule传递给SQL查询以将值插入到表中.我键入的代码在下面,似乎不起作用(问题在于我将字符串传递给查询的方式.

string lbSites = "";

protected void Button1_Click1(object sender, EventArgs e)
{
    string cns = "server=abc;database=testDB;Trusted_Connection=True";
    using (SqlConnection con = new SqlConnection(cns))
    {
        using (SqlCommand command = con.CreateCommand())
        {
            command.CommandText = "INSERT INTO Activity (Hostname,Site,Status,System_Dept,Business_Dept)"
                + "SELECT * FROM Inventory WHERE Site IN ("+lbSites+");"
                ; 
            con.Open();
            command.Parameters.AddWithValue("@lbSites", lbSites);
            command.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ListBox1.Items.Count > 0)
    {
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected)
            {
                lbSites += "'" + ListBox1.Items[i].Value + "', ";
            }
        }
    }
}

解决方法:

每次发回时,lbSites的值都会丢失.将其保留在您的ViewState中.

此外,您不需要command.Parameters.AddWithValue(“ @ lbSites”,lbSites);因为您的sql中没有@lbSites参数.

标签:listbox,where-in,sql-server-2008,c
来源: https://codeday.me/bug/20191201/2079589.html