0

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?

2
  • join both tables. Commented Nov 30, 2020 at 16:32
  • Why do you want to "loop" at all? SQL is a set based language so looping is one of the last things you want to actually do. When writing SQL you want to implement set based operations, not iterative ones Commented Nov 30, 2020 at 16:37

1 Answer 1

1

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.

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

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.