I had a Program in c# which would run queries using a dynamically created string which would be used as a query.
Now due to possibility of SQL injection, I want to use parameterized queries to generate the same.
Was looking at Parameterized dynamic sql query and that is mostly what I want, but then I want multiple parameters in the same sequence and not in different sequences. i.e I want something like
(Where value in ({0}, {1}, {2}), param0 , param1, param2 )
The answer in that thread is
SqlCommand cmd = new SqlCommand();
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.Append("SELECT name, memberid FROM members ");
var i = 1;
foreach (string item in keywords)
{
sqlBuilder.Append(i == 1 ? " WHERE " : " AND ");
var paramName = "@searchitem" + i.ToString();
sqlBuilder.AppendFormat(" Name LIKE {0} ", paramName);
cmd.Parameters.AddWithValue(paramName, "%" + item + "%");
i++;
}
cmd.CommandText = sqlBuilder.ToString();
If I use this for my query, this would generate something like
where Value In param0 and value in param1 and value in param2
which if I'm not mistaken is terrible in terms of server performance.
So how do I get something similar to
sqlBuilder.AppendFormat(" Name IN {0} , {1} , {2} ", paramName0 , paramName1 , paramName2 );
for a parameterized dynamic query?
All the methods that I have tried compiles ok, but then returns run time errors.
Can't seem to figure what I'm doing wrong. :( Any help?