Pass Array Parameter in SqlCommand

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

    Since there is a method on

    SqlCommand.Parameters.AddWithValue(parameterName, value)
    

    it might be more convenient to create a method accepting a parameter (name) to replace and a list of values. It is not on the Parameters level (like AddWithValue) but on command itself so it's better to call it AddParametersWithValues and not just AddWithValues:

    query:

    SELECT * from TableA WHERE Age IN (@age)
    

    usage:

    sqlCommand.AddParametersWithValues("@age", 1, 2, 3);
    

    the extension method:

    public static class SqlCommandExtensions
    {
        public static void AddParametersWithValues(this SqlCommand cmd,  string parameterName, params T[] values)
        {
            var parameterNames = new List();
            for(int i = 0; i < values.Count(); i++)
            {
                var paramName = @"@param" + i;
                cmd.Parameters.AddWithValue(paramName, values.ElementAt(i));
                parameterNames.Add(paramName);
            }
    
            cmd.CommandText = cmd.CommandText.Replace(parameterName, string.Join(",", parameterNames));
        }
    }
    

提交回复
热议问题