Skip to content
Advertisement

Microsoft SQL Server – Convert column values to list for SELECT IN

I have this (3 int columns in one table)

Int1 Int2 Int3
---------------
 1    2    3

I would like to run such query with another someTable:

SELECT * FROM someTable WHERE someInt NOT IN (1,2,3) 

where 1,2,3 are list of INTs converted to a list that I can use with SELECT * NOT IN statement

Any suggestions how to achieve this without stored procedures in Micorosft SQL Server 2019 ?

Advertisement

Answer

If you want rows in some table that are not in one of three columns of another table, then use not exists:

select t.*
from sometable t
where not exists (select 1
                  from t t2
                  where t.someint in (t2.int1, t2.int2, t2.int3)
                 );

The subquery returns a row where there is a match. The outer query then rejects any rows with a match.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement