0

I am not an expert of SQL and what I am trying to achieve is the following.

I have a list of integers called PersonIds. First of all I need to transform this list of integers to a list of strings. Why? Because as far as I have understood for the WHERE .. IN condition in SQL this is the kind of variable I need to feed to the query.

Then I need to modify the list of strings in order to prevent SQL injection and therefore inserting @ before every Id of the list.

At last I create the query and feed the list I just created.

What I tried to do is:

var listIds = string.Join(",@", PersonIds, 0, PersonIds.Count()));
var query = $"DELETE FROM PersonTable WHERE PersonId IN (@{listIds})";

There is something I am doing wrong. To recap I need to steps:

  1. preparing a list (including mechanism to avoid SQL injection) that I need to feed to the query
  2. create the query using as argument the list I created

Thanks in advance!

2
  • What is the likely value of PersonIds.Count? Is it ever likely to be > 2000? Commented Mar 20, 2018 at 23:42
  • @mjwills no it's likely to be max 10 Commented Mar 21, 2018 at 8:15

1 Answer 1

7

Perhaps the simplest way is to add some Dapper:

List<int> listIds = ...
connection.Execute("DELETE FROM PersonTable WHERE PersonId IN @listIds",
        new { listIds });

Dapper does all the hard work of figuring out how to parameterize that, while still staying almost close to regular TSQL. You can also optionally enable string_split usage if you're using recent versions of SQL Server, to minimize the parameter count and query-plan cache size.

Note that the missing parentheses is deliberate and intentional - dapper treats this slightly differently to the regular IN (@foo, @bar) syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.