-1

I have int list and I need to convert it so it will be possible to send it to IN operator from c# code. I tried a lot of manipulate but got error every time.

string idsList = "(" + string.Join(",", ids.Select(id => $"'{id.ToString()}'")) +")";

 var sql = @"SELECT * from user
WHERE user.id IN (@idsList))";
        using (var connection = OpenConnection())
        {
            var results = await connection.QueryAsync<UserQueryResponse>(sql, new
            {
                idsList= idsList,
            });
            return results.Select(raw =>raw.CreateModel());
        }
    }

The column type of user.id is string

j.her
  • 187
  • 1
  • 2
  • 11

2 Answers2

0

I assume you are using Dapper. Have a look at this answer. Try deleting the parenthesis in your query.

var sql = @"SELECT * from user WHERE user.id IN @idsList";
        using (var connection = OpenConnection())
        {
            var results = await connection.QueryAsync<UserQueryResponse>(sql, new
            {
                idsList= idsList,
            });
            return results.Select(raw =>raw.CreateModel());
        }
    }
ibrahimozgon
  • 1,137
  • 1
  • 12
  • 19
0

You should not use the parameter delimiter (@) if your query is not parametrized.

Warning: Do note that if the ids list were not of type int you could have had a SQL Injection problem.

List<int> ids = new List<int>{ 7, 14 ,21 };
string idsList = "(" + string.Join(",", ids.Select(id => $"'{id.ToString()}'")) +")";
/* Your idsList variable will contain "('7','14','21')" */
var sql = @"SELECT * from user WHERE user.id IN " + idsList;

A better approach would be using parameters:

StringBuilder idsList = new StringBuilder("in (");

for (int i=0; i< ids.Count; i++)
{
    // Dynamically write the IN clause
    if (i > 0) ? idsList.Append(",");
    idsList.Append("@param" + i.ToString());
    // Add the parameter that was added to the IN
    command.Parameters.AddWithValue("@param" + i.ToString(), idsList[i])
}
idsList.Append(")");
/* idsList will cointain "in (@param0, @param1, @param2)" */
Cleptus
  • 3,446
  • 4
  • 28
  • 34