Click here to Skip to main content
15,888,065 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How i cam do parameterized in clause on list of strings

What I have tried:

List<string> x= new List<string>(){"one","two","three"}
select * from Employee where EMP_NAME IN(@names)
How i can make the list of string object to parameterized value
I tried as select * from Employee where EMP_NAME IN(String.Join(",",x)) but it didn't worked as it making as('one,two.three') ideally it should be("one","two","three") any idea how i can achieve this
Posted
Updated 31-Mar-16 9:25am
v2

1 solution

If you're using .NET, try Dapper[^]:
C#
using (var connection = new SqlConnection("..."))
{
    var results = connection.Query<Employee>("SELECT * FROM Employee WHERE Emp_Name In @Names", new 
    { 
        Names = new List<string> { "One", "Two", "Three" }
    });
}

List Support[^]

If you can't use Dapper, you'll have to add each item as a separate parameter:
C#
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(string.Empty, connection))
{
    var sb = new StringBuilder();
    sb.Append("SELECT * FROM Employee WHERE Emp_Name In (");
    
    for (int index = 0; index < list.Count; index++)
    {
        if (index != 0) sb.Append(", ");
        
        string parameterName = "@Name" + index;
        command.Parameters.AddWithValue(parameterName, list[index]);
        sb.Append(parameterName);
    }
    
    sb.Append(')');
    command.CommandText = sb.ToString();
    
    ...
}
 
Share this answer
 
v2
Comments
MYQueries1 31-Mar-16 15:42pm    
I can't use wrappers. Is there any conventional way of doing this?
Richard Deeming 31-Mar-16 15:46pm    
Then you'll have to add each item as a separate parameter. I've updated my answer with an example.
Sascha Lefèvre 31-Mar-16 17:49pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900