views:

77

answers:

4

Here's what I'm trying do to in a single SQL Server procedure:

@ID1 int

select ID2 from TableA where ID1 = @ID1

(for each selected @ID2)
    select * from TableB where ID2 = @ID2

Any ideas?

+1  A: 

Try this:

select * from TableB b where exists (select top 1 * from TableA a where a.ID2 = b.ID2)
Valkyrie
+10  A: 

That can be done in a single statement:

SELECT b.*
  FROM TABLE_B b
  JOIN TABLE_A a ON a.id2 = b.id2
 WHERE a.id1 = @ID1

But this means that there will be duplicates if more than one record in TABLE_A relates to a TABLE_B record. In that situation, use EXISTS rather than adding DISTINCT to the previous query:

SELECT b.*
  FROM TABLE_B b
 WHERE EXISTS(SELECT NULL
                FROM TABLE_A a
               WHERE a.id2 = b.id2
                 AND a.id1 = @ID1)

The IN clause is equivalent, but EXISTS will be faster if there are duplicates:

SELECT b.*
  FROM TABLE_B b
 WHERE b.id2 IN (SELECT a.id2
                   FROM TABLE_A a
                  WHERE a.id1 = @ID1)
OMG Ponies
and A.ID1 = @ID1...
Jonathan
+1  A: 
SELECT * 
FROM TableB 
WHERE ID2 IN (SELECT ID2 FROM TableA WHERE ID1 = @ID1)

Generally speaking, you don't want to do any kind of looping in SQL Server. Try using "Set based" operations.

StingyJack
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
The formatting is sucky for SQL, so I dont bother with it. If its really bugging you, you are free to edit the post.
StingyJack
A: 

For each doesnt work in sql, you must use cursors.

declare @id int declare @id2 int

declare mycursor cursor for select id2 from tablea where id=@id

open mycursor

fetch next from mycursor into @id2

while @@fetch_status = 0 begin

your code here

fetch next from mycursor into @id2 end close mycursor deallocate mycursor

cursors are evil!
Jonathan
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
No, i always use it and i never have problems with that, but, if he need a single clause, he can use exists or join clause, but cursors and forech do the same effect
Actually, yes - cursors **ARE** the work of the devil, if you have more than 5 concurrent users and more than 1'000 rows of data - don't use them
marc_s
el-chente, Changing from loop to set based ops can reap untold magnitudes of performance increase (even for smaller sets), but may be a bit more difficult up front to implement.
StingyJack