-2

I have an SQL where clause: -

where table1.resource in @ListOfRes

I'm trying to add to the SQL command like this:-

command.Parameters.AddWithValue("@ListOfRes", "'1','2'");

The result I'm looking for is: -

where table1.resource in ('1','2')

But I can't seem to build a string this way, is there a different data type I need to be using?

6
  • 1
    You can't pass lists this way. There are alternatives, among those manually splitting strings and table-valued parameters (and fully dynamic SQL, but that's a last resort). Commented Aug 17, 2020 at 14:38
  • 4
    Short answer - use Dapper. Longer answer - table valued parameter (stackoverflow.com/a/45407499/34092). Commented Aug 17, 2020 at 14:39
  • This might be a bad answer but it seems you can do that directly in the command text instead of through a parameter. But if the list is exposed to the front end environment it leaves you exposed to injection. Commented Aug 17, 2020 at 14:57
  • Related: stackoverflow.com/questions/337704/… Commented Aug 17, 2020 at 14:58
  • SELECT * FROM Tags WHERE '|ruby|rails|scruffy|rubyonrails|' LIKE '%|' + Name + '|%' This is almost what I need, but I need to do it for int, is that possible? Commented Aug 18, 2020 at 12:38

2 Answers 2

1

Nope, Not working. This is not how SQL works, regardless what you do.

IN (@variable) takes the content of the variable as ONE ELEMENT. There is no way to put multiple elements in it. Live with it. You need one variable for every element, or another approach (temp file, then using a join etc.)..

This simply is not a supported approach.

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

Comments

0

Since SQL Server 2008, there is a solution, table valued parameters. See C# with SQL Server SELECT WHERE IN with data list

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.