1

Let me explain... I have one table which has a column that contains a delimited list of numbers which need to be used to return data from another table. (Don't ask, I did not design this!). EG:

Set @DelimitedList = (Select stupid_column from Table_One)

This results in @DelimitedList containing '1,2,3'; I then want to use this in a 'Where' clause for a subsequent query... i.e

Select * from Table_Two where int_column in (@DelimitedList)

Sadly this does not work as SQL tries to convert @DelimitedList to an integer which fails. Is there some way I can 'cast' or 'convert' my string list into an integer array?

Many thanks in advance

Nibbo
  • 17
  • 4

2 Answers2

2

Using dynamic SQL, which I do not necessarily recommend, you may be able to do as follows:

EXEC ('Select * from Table_Two where int_column in (' + @DelimitedList + ')')

You can find more info, here.

Thejaka Maldeniya
  • 1,076
  • 1
  • 10
  • 20
  • Thanks Thejaka, this does work but I think I favour valex's version below. I did try EXEC but got it all wrong so your solution has cleared up how I could have done it and will be useful in the future. – Nibbo Jan 15 '14 at 07:25
0

This can be done following way: Replace

WHERE    int_column in (@DelimitedList)

with

WHERE    ','+@DelimitedList+',' LIKE '%,'+CAST(int_column AS Varchar(10))+',%'

Also it can depend on your RDBMS. For example in MySQL you can use FIND_IN_SET() function.

valex
  • 23,966
  • 7
  • 43
  • 60