Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple parameters to SQL command in one statement?

Tags:

c#

sql

I have six lines of parameters like this:

    cmd.Parameters.AddWithValue("@variable1", myvalue1);
    cmd.Parameters.AddWithValue("@variable2", myvalue2);
    cmd.Parameters.AddWithValue("@variable3", myvalue3);

and so on.

Is there any way to compress this a bit without directly inserting in the cmd.CommandText?

Edit: I guess I could have used a good old fashioned array. I've decided to stick with this though.

like image 854
user3808188 Avatar asked Jul 23 '14 18:07

user3808188


2 Answers

I took the question literally: "...in one statement" :)

Steve code is nice but it can be simplified a bit more using the most canonical SqlParameter constructor and implicit arrays declaration:

cmd.Parameters.AddRange(new []
    {
        new SqlParameter("@variable1", myValue1),
        new SqlParameter("@variable2", myValue2),
        new SqlParameter("@variable3", myValue3),
    });
like image 135
Larry Avatar answered Oct 17 '22 03:10

Larry


I think this will read very nicely as a one liner like this:

Usage:

// One liner to create and set SqlCommand parameters
cmd.SetParameters(Parameter("@variable1", myvalue1), Parameter("@variable2", myvalue2), Parameter("@variable3", myvalue3));

To support the one liner you need to create a function to wrap the Sql Parameter as a semantic bundle (Tuple like) as follows:

public SqlParameter Parameter(string name, object value)
{
    return new SqlParameter(name, value);
}

Create a static class with an extension method to give us the syntactic sugar we are looking for. Notice the use of the params keyword which allows the multiple parameters in the above call to SetParameters.

public static class SqlDataUtils
{
    public static void SetParameters(this SqlCommand command, params SqlParameter[] parameters)
    {
        command.Parameters.AddRange(parameters);
    }
}

This answer is inspired by the accepted answer to Key value pairs in C# Params by Bryan Watts

like image 27
warren.sentient Avatar answered Oct 17 '22 05:10

warren.sentient