tags:

views:

285

answers:

5
Select a, b, c from table where a in (1, 2, 3)

What if the list is in a column?

I try this will error:

Select a, b, c from a in b

Sorry for not clear my question.

It's not about join or in (select b from table)

Column b type is nvarchar, data is a list, like this '1,2,5'

Column a type is int.

A: 

I think you want to JOIN the tables?

SELECT a, b, c
FROM a
JOIN b ON a.ID=b.ID
JerSchneid
column b is a list.
March
A: 

In SQL, a column is normally of one of the so-called "scalar" data types: numbers, date/time, strings -- see e.g. MSDN. If you explain better in what sense you got "a list" into column b, and how, e.g. show us the CREATE TABLE a statement, we can maybe help you better!

Alex Martelli
+1  A: 

After reading your question, this is what you want:

SELECT
    a,b,c
FROM
    tblA
WHERE
    b LIKE CAST(a as nvarchar) + ',%'
    OR b LIKE '%,' + CAST(a as nvarchar) + ',%'
    OR b LIKE '%,' + CAST(a as nvarchar)

That should do it.

Eric
No it wouldn't. Notice the placement of the commas. Already got that covered. Booyah.
Eric
@Eric: You're right, I'll remove the comment.
Andomar
+1  A: 

Many answers pointing in the right direction, but I think this one will really work:

SELECT a, b, c
FROM table
WHERE ',' + b + ',' LIKE '%,' + CAST(a as varchar) + ',%'

You can speed this up by enforcing B starts and ends with a comma. Or even better, normalize the database and move the column B to its own table with a one-to-many relation.

Andomar
A: 

See http://stackoverflow.com/questions/813124/need-sql-query-help-matching-a-stored-procedure-list-parameter-against-individua/813352#813352. It shows how to write a UDF that will take your "list" column and return a table that you can use to join against the one you're selecting from.

John Saunders