0

SQL Server

I have a parameter that contains a comma delimited string:

'abc,def,ghi'

I want to use that string in a IN statement that would take my parameter like this:

select * from tableA where val IN ('abc','def','ghi')

Any ideas on how I would do this?

webdad3
  • 8,893
  • 30
  • 121
  • 223

4 Answers4

1

If using dynamic SQL is an option, this can be executed:

SELECT 'SELECT * FROM tableA WHERE val IN (' +
       '''' + REPLACE('abc,def,ghi', ',', ''',''') + ''')'

Basically, the REPLACE() function separates each item by ',' instead of just ,.

Daniel Neel
  • 1,197
  • 13
  • 28
1

The simplest way would be to do something like this:

SELECT *
FROM TableName
WHERE ',' + commaDelimitedString + ',' LIKE '%,' + FieldName + ',%'

But be careful about SQL injection. You might want to parameterize it.

Rabbit
  • 507
  • 3
  • 9
0

You can use this SQL to 'pivot' a comma-separated string into a table;

DECLARE @badData TABLE (id INT NOT NULL, txt NVARCHAR(max));

INSERT INTO @badData
VALUES (1, 'foo,bar,baz'), (2, NULL);;

-- the idea is to recursively 'pop' a value from the start of the string, splitting it into 'head' and 'tail' components
WITH unpacked (id, head, tail)
AS (
  SELECT id, LEFT(txt, CHARINDEX(',', txt + ',') - 1), STUFF(txt, 1, CHARINDEX(',', txt + ','), '')
  FROM @badData

  UNION ALL

  SELECT id, LEFT(tail, CHARINDEX(',', TAIL + ',') - 1), STUFF(tail, 1, CHARINDEX(',', tail+ ','), '')
  FROM unpacked
  WHERE tail > ''
  )
SELECT id, head
FROM unpacked
ORDER BY id

You could stick this result into a common table expression, then write a where clause like

select * from tableA where val IN (select head from unpacked)

heavily plagiarised from https://stackoverflow.com/a/5493616/6722

Community
  • 1
  • 1
Steve Cooper
  • 20,542
  • 15
  • 71
  • 88
-3

Many programming languages have a split() function, for example in Ruby

'123,456,789'.split "," => ["123", "456", "789"]

lee
  • 417
  • 3
  • 13