2

I'm trying to figure out the best query to accomplish the following.

I have 2 tables that are related by an ID column.

Table1

ID
UserID

Table2

ID
SomeDataColumn

What I need to do is select a list of IDs from Table1 where my UserID='5' or some number. This should return multiple rows with respective IDs. Then I need to delete all rows from Table2 that contain any ID from my returned list of IDs from Table1.

The only way I could figure out how to do this was to select all of the rows from my first table, put them in a cursor, and then loop through each one running a Delete query for each ID. But it seems there must be a more efficient way to do this with a join or something.

Any ideas? Thanks all!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
j00b
  • 405
  • 1
  • 5
  • 12

4 Answers4

5

This might get you there:

delete from Table2 where ID in (select ID from Table1 where UserID = '5')

You're right to think there is a better way in SQL

Community
  • 1
  • 1
Tim Lehner
  • 14,813
  • 4
  • 59
  • 76
3

3 ways

DELETE   FROM SomeTable
WHERE id IN(SELECT id FROM AnotherTAble WHERE USerID = 5 and id is not null)

DELETE  s
 FROM SomeTable s
JOIN AnotherTAble  a on s.ID = a.ID
WHERE a.USerID = 5


DELETE  s
 FROM SomeTable s
WHERE EXISTS (SELECT 1 from AnotherTAble  a WHERE a.ID = S.ID
AND a.USerID = 5)
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
0
 DELETE Table2
 WHERE ID IN (
     SELECT ID FROM Table1
     WHERE UserID=5
 )

That does it?

Francis P
  • 13,377
  • 3
  • 27
  • 51
0

Use a join,

DELETE FROM [Table2] 
FROM [Table2] as t2 
INNER JOIN [Table1] as t1 ON t2.[ID] = t1.[ID] 
WHERE t1.[UserID] = 5; 
Russell Hart
  • 1,842
  • 13
  • 20