DevPerson
DevPerson

Reputation: 9

How to use SQL query with a column of values for where?

How can I loop though a column of IDs I created with in a 2nd select query with a WHERE.

Example table of ids to loop through:

1

Here is what I got so far:

WITH myTable  
AS (  
    select myKey as myKey  
    from dbo.table  
    Where column2 = 'x'  
    GROUP BY myKey  
)  
SELECT *  
FROM table2  
WHERE table2.key = myKey

I can't loop through table2 with my column of values. How can I do it?

Upvotes: 0

Views: 29

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

You can use in:

SELECT *
FROM table2
WHERE table2.key IN (SELECT mt.myKey FROM myTable mt);

Given that the mykey is unique, you can also use JOIN and EXISTS.

Upvotes: 1

Related Questions