Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass sqlparameter to IN()? [duplicate]

For some reason the Sqlparameter for my IN() clause is not working. The code compiles fine, and the query works if I substitute the parameter with the actual values

StringBuilder sb = new StringBuilder();             foreach (User user in UserList)             {                 sb.Append(user.UserId + ",");             }              string userIds = sb.ToString();             userIds = userIds.TrimEnd(new char[] { ',' });   SELECT userId, username  FROM Users  WHERE userId IN (@UserIds)  
like image 383
chobo Avatar asked Feb 21 '12 20:02

chobo


People also ask

How to pass SqlParameter in c#?

Using parameterized queries is a three-step process: Construct the SqlCommand command string with parameters. Declare a SqlParameter object, assigning values as appropriate. Assign the SqlParameter object to the SqlCommand object's Parameters property.

How many parameters are passed when an object of SqlCommand class is created?

This is another constructor of SqlCommand Class that has three parameters. The first parameter is a string type that is used to assign a SQL query or stored procedure in string format. The second parameter is a SqlConnection type that is used to assign a SqlConnection to the SqlCommand.

How do you parameterize a clause in SQL?

For SQL Server 2008, you can use a table valued parameter. It's a bit of work, but it is arguably cleaner than my other method. Please try to avoid var metadata = SqlMetaData. InferFromValue(firstRecord, columnName);


2 Answers

You have to create one parameter for each value that you want in the IN clause.

The SQL needs to look like this:

SELECT userId, username  FROM Users  WHERE userId IN (@UserId1, @UserId2, @UserId3, ...)  

So you need to create the parameters and the IN clause in the foreach loop.
Something like this (out of my head, untested):

StringBuilder sb = new StringBuilder(); int i = 1;  foreach (User user in UserList) {     // IN clause     sb.Append("@UserId" + i.ToString() + ",");      // parameter     YourCommand.Parameters.AddWithValue("@UserId" + i.ToString(), user.UserId);      i++; } 
like image 95
Christian Specht Avatar answered Sep 28 '22 12:09

Christian Specht


Possible "cleaner" version:

StringBuilder B = new StringBuilder(); for (int i = 0; i < UserList.Count; i++)      YourCommand.Parameters.AddWithValue($"@UserId{i}", UserList[i].UserId); B.Append(String.Join(",", YourCommand.Parameters.Select(x => x.Name))); 
like image 21
mrogunlana Avatar answered Sep 28 '22 13:09

mrogunlana