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)
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.
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.
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);
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++; }
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With