Pass Array Parameter in SqlCommand

前端 未结 12 1880
情深已故
情深已故 2020-11-22 08:27

I am trying to pass array parameter to SQL commnd in C# like below, but it does not work. Does anyone meet it before?

string sqlCommand = \"SELECT * from Ta         


        
12条回答
  •  粉色の甜心
    2020-11-22 09:26

    Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16").

    But you can pass your parameter as an array serialized to XML or JSON:

    Using nodes() method:

    StringBuilder sb = new StringBuilder();
    
    foreach (ListItem item in ddlAge.Items)
      if (item.Selected)
        sb.Append("" + item.Text + ""); // actually it's xml-ish
    
    sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
        SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
    sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
    sqlComm.Parameters["@Ages"].Value = sb.ToString();
    

    Using OPENXML method:

    using System.Xml.Linq;
    ...
    XElement xml = new XElement("Ages");
    
    foreach (ListItem item in ddlAge.Items)
      if (item.Selected)
        xml.Add(new XElement("age", item.Text);
    
    sqlComm.CommandText = @"DECLARE @idoc int;
        EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
        SELECT * from TableA WHERE Age IN (
        SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
        EXEC sp_xml_removedocument @idoc";
    sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
    sqlComm.Parameters["@Ages"].Value = xml.ToString();
    

    That's a bit more on the SQL side and you need a proper XML (with root).

    Using OPENJSON method (SQL Server 2016+):

    using Newtonsoft.Json;
    ...
    List ages = new List();
    
    foreach (ListItem item in ddlAge.Items)
      if (item.Selected)
        ages.Add(item.Text);
    
    sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
        select value from OPENJSON(@Ages))";
    sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
    sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);
    

    Note that for the last method you also need to have Compatibility Level at 130+.

提交回复
热议问题