sqllover999 sqllover999 - 3 months ago 9
SQL Question

Passing id from one table to another and getting a total union result in SQL Server

I am trying to obtain a result where id is passed from another table in this like expression.

Eg.

Id
is
B001,B002,B003...... B009
in
tblname2
and after passing all the id to
tblname1
, I want the combine result using
union
:

select *
from tblname1
where id like '%idfromtblname2%'


i.e

select *
from tblname1
where id like '%B001%'

union

select *
from tblname1
where id like '%B002%'

union

select *
from tblname1
where id like '%B003%'

Answer

Let me offer another version of this - Don't pass a parameter, just use EXISTS() :

SELECT * FROM tblname1 t 
WHERE EXISTS(SELECT 1 FROM tblname2 s
             WHERE t.id LIKE '%' + s.<Col> + '%')

But, all depends on how you store your data .