3

Possible Duplicate:
Parameterizing an SQL IN clause?
Comma-separated value insertion In SQL Server 2005

I'm trying to search in my database using where in clause, but my string is in follow format:

'233052,57516351,254689'

I need to do an consult in my database using the following query:

SELECT * FROM myTable WHERE field IN (@list_string)

How I do to make this action?

9
  • 3
    What version of SQL Server are you using? I suggest reading Arrays and Lists in SQL Server, by Erland Sommarskog. Commented Dec 27, 2012 at 13:57
  • I'm using SQL Server 2008 Commented Dec 27, 2012 at 13:59
  • 1
    Then Table-Valued Parameters are the way to go. Commented Dec 27, 2012 at 14:00
  • This question has been asked before; look at [the answer here][1] [1]: stackoverflow.com/a/1033208/96505 Commented Dec 27, 2012 at 14:00
  • 1
    @TonyHopkinson - For a variable list of values, you have to use one of these options. TVPs are probably the best option, when it comes to SQL Server. Commented Dec 27, 2012 at 14:03

3 Answers 3

5

Use Table-valued parameters, introduced in SQL Server 2008.

These let you pass in a table structure that you can use to query on.

For other options, I suggest reading Arrays and Lists in SQL Server, by Erland Sommarskog.

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

Comments

2

I've been using Itai Goldstein's Split function for years for this very situation. You could then do the following:

SELECT * 
FROM [myTable] 
WHERE [field] IN (
    SELECT [Data]
    FROM [dbo].[Split] (@list_string, ',')
);

1 Comment

Nice, I'll remember that one.
0

Try EXEC of sql statement concatenation:

declare @sql varchar(200)
set @sql='SELECT * FROM myTable WHERE field IN ('+@list_string+')'
exec(@sql)

3 Comments

Sql Injection. Build a parameterised query Select * from MyTable Where field = @p1 [Or field = @p2] using the count of values in the list, then assign the values to the parameters as a safer option.
@Tony I agree if the list_string is client data, but if the list_string source list is safe and already validated, this will be the fastest execution and best performance query.
Or query takes longer to parse, because it's longer, doubt it's going to take longer to execute though. The comment was just a heads up for the many many peoples who keep perpetuating sql injection mistake.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.