Pass Array Parameter in SqlCommand

前端 未结 12 1876
情深已故
情深已故 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:05

    If you are using MS SQL Server 2008 and above you can use table-valued parameters like described here http://www.sommarskog.se/arrays-in-sql-2008.html.

    1. Create a table type for each parameter type you will be using

    The following command creates a table type for integers:

    create type int32_id_list as table (id int not null primary key)
    

    2. Implement helper methods

    public static SqlCommand AddParameter(this SqlCommand command, string name, IEnumerable ids)
    {
      var parameter = command.CreateParameter();      
    
      parameter.ParameterName = name;
      parameter.TypeName = typeof(T).Name.ToLowerInvariant() + "_id_list";
      parameter.SqlDbType = SqlDbType.Structured;
      parameter.Direction = ParameterDirection.Input;
    
      parameter.Value = CreateIdList(ids);
    
      command.Parameters.Add(parameter);
      return command;
    }
    
    private static DataTable CreateIdList(IEnumerable ids)
    {
      var table = new DataTable();
      table.Columns.Add("id", typeof (T));
    
      foreach (var id in ids)
      {
        table.Rows.Add(id);
      }
    
      return table;
    }
    

    3. Use it like this

    cmd.CommandText = "select * from TableA where Age in (select id from @age)"; 
    cmd.AddParameter("@age", new [] {1,2,3,4,5});
    

提交回复
热议问题