Using SqlParameter in SqlCommand is a great way to pass variable into SQL statement and prevent SQL Injection, it is rather simple to implement as well, basically all you need to do is to declare the parameter name in your SQL statement or stored procedure and make sure that you add the parameter with the specified parameter name into the SQL command parameters. Here’s an example of basic implementation of SqlParameter:
var sqlCommand = new SqlCommand(); var sql = "SELECT * FROM TBL_USER_MASTER WHERE USER_NAME = @parameter"; sqlCommand.CommandText = sql; // Add The Parameter sqlCommand.Parameters.AddWithValue("parameter", "sebastian"); // Execute the query and do something with it var reader = sqlCommand.ExecuteReader();
That is rather easy and simple, isn’t it? But what if you want to use the SqlParameter in conjunction with the IN clause? For an example, you have a list of strings or an array of string which you are going to include in an IN clause as a condition, how to do it with SqlParameter? Well, you can not straight away pass the list of strings or the string array into the value of the SqlParameter as it will cause an exception.
However the approach is rather similar, instead of passing the entire list or array of string as the SqlParameter value you will need to define individual parameter for each string and fortunately you do not have to define each parameter one by one as you can just loop through the list of strings that you have and add them into the parameter list. The code snippet below will show you an example how to do it (full example):
Where the method used in the code snippet above will produce the following SQL statement:
SELECT * FROM TBL_USER_MASTER WHERE USER_ID IN (@idParam0,@idParam1,@idParam2,@idParam3,@idParam4) OR USER_NAME IN (@nameParam0,@nameParam1,@nameParam2)
And if you notice you can use the method above not only for string list, but also works with other data types (e.q int). You can even simplify the method above using LINQ, but I’m not going to show you how to do it here as the purpose is just to show you how to implement SqlParameter with IN clause.