Pass Array Parameter in SqlCommand

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

    I wanted to expand on the answer that Brian contributed to make this easily usable in other places.

    /// 
    /// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
    /// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN (returnValue))
    /// 
    /// The SqlCommand object to add parameters to.
    /// The array of strings that need to be added as parameters.
    /// What the parameter should be named.
    protected string AddArrayParameters(SqlCommand sqlCommand, string[] array, string paramName)
    {
        /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually. 
         * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
         * IN statement in the CommandText.
         */
        var parameters = new string[array.Length];
        for (int i = 0; i < array.Length; i++)
        {
            parameters[i] = string.Format("@{0}{1}", paramName, i);
            sqlCommand.Parameters.AddWithValue(parameters[i], array[i]);
        }
    
        return string.Join(", ", parameters);
    }
    

    You can use this new function as follows:

    SqlCommand cmd = new SqlCommand();
    
    string ageParameters = AddArrayParameters(cmd, agesArray, "Age");
    sql = string.Format("SELECT * FROM TableA WHERE Age IN ({0})", ageParameters);
    
    cmd.CommandText = sql;
    


    Edit: Here is a generic variation that works with an array of values of any type and is usable as an extension method:

    public static class Extensions
    {
        public static void AddArrayParameters(this SqlCommand cmd, string name, IEnumerable values) 
        { 
            name = name.StartsWith("@") ? name : "@" + name;
            var names = string.Join(", ", values.Select((value, i) => { 
                var paramName = name + i; 
                cmd.Parameters.AddWithValue(paramName, value); 
                return paramName; 
            })); 
            cmd.CommandText = cmd.CommandText.Replace(name, names); 
        }
    }
    

    You can then use this extension method as follows:

    var ageList = new List { 1, 3, 5, 7, 9, 11 };
    var cmd = new SqlCommand();
    cmd.CommandText = "SELECT * FROM MyTable WHERE Age IN (@Age)";    
    cmd.AddArrayParameters("Age", ageList);
    

    Make sure you set the CommandText before calling AddArrayParameters.

    Also make sure your parameter name won't partially match anything else in your statement (i.e. @AgeOfChild)

提交回复
热议问题