0

I have a column in database that stores an array of numbers in a nvarchar string and the values look like this "1,5,67,122"

Now, I'd like to use that column value in a query that utilizes IN statement

However, if I have something like

WHERE columnID IN (@varsArray);

it doesn't work as it sees @varsArray as a string and can't compare it to columnID which is of INT type.

how can I convert that variable to something that could be used with a IN statement?

2
  • DON'T DO THAT! CSV data in columns is EVIL! Commented Nov 5, 2013 at 19:11
  • that is an existing design that can't be changed at the moment Commented Nov 5, 2013 at 19:14

4 Answers 4

3

You need dynamic SQL for that.

exec('select * from your_table where columnID in (' + @varsArray + ')')

And BTW it is bad DB design to store more than 1 value in a column!

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

Comments

0

alternatively you can parse your variable with finding a split user defined function on the internet and enter each number into a temp table and then join the temp table

but the person who answered above is correct this is bad database design

create a table so you can join it based on some id, and all the answers will be in a table (temporary or not)

Comments

0

One other option is to use a User Defined Table-Valued function that takes a delimited string as input and generates a table with one row per value as its output (see This SO question), and then, using Cross Apply, join the table itself to the output of that UDF.

These techniques are useful to have in your trick-bag anyway.

Comments

0

Unfortunately we're forced to work against bad data designs sometimes...

I've seen this done by building and calling a SQL function that splits out the numbers and returns them in a table. Then you could run your columnID against that temp table to see if it exists.

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.