• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 190
  • Last Modified:

In SQL, for each value returned how do I delete rows in another table identified by each returned values?

In SQL, for each value returned how do I delete rows in another table identified by each returned values

Consider, I have table A:

key | name_key
1       matt d.
2       keith r.
3       bob h.

In table B I have

name_key | cars
1       koenigsegg
1       veyron
1       enzo
2       astra
3       veyron

Basically, I want the command to delete the owners of veyrons from table A (1 and 3) as well as the veyron entry in table B.
However there should be enough logic to know not to remove entry 1 from table A because he owns other cars.

I'm thinking something along
0
Matt_Du
Asked:
Matt_Du
3 Solutions
 
j_s_kelleyCommented:
Your request doesn't make sense.  If you want to delete the owners of Veyrons in Table A, that would include owner 1.  You can't delete him and leave him in.  I'm gonna take a shot that what you mean is delete that Veyron's and if there are any users that no longer have cars in table B, remove them as well.  You can do this in 2 steps.  See the code.  If this is not what you want to do, please clarify.
Delete From B where Cars = 'Veyron'
Delete From A where key not in (Select name_key from B)

Open in new window

0
 
reb73Commented:
Try the sample code below (keep a backup of your original tables just in case!) -

 
DELETE T1
FROM TableA T1
WHERE EXISTS (SELECT NULL FROM  TableB WHERE TableB.name_key = T1.name_key AND cars = 'veyron')
AND NOT EXISTS (SELECT NULL FROM TableA T2 WHERE T2.name_key = T1.name_key AND cars <> 'veyron')
 
DELETE TableB
WHERE cars = 'veyron'

Open in new window

0
 
Raja Jegan RSQL Server DBA & ArchitectCommented:
Hope this helps:
declare @cnt int,
@key int,
@cars varchar(100);
declare cursor del_cur for
select name_key,cars
from tableB
where cars = 'veyron';
 
OPEN del_cur;
 
FETCH NEXT FROM del_cur
INTO @key, @cars;
 
WHILE @@FETCH_STATUS = 0
BEGIN
   set @cnt = (select count(*) from tableB where name_key = @key and cars = @cars);
   IF @cnt = 1
   begin
      delete from tableB where name_key = @key and cars = @cars;
      delete from tableA where key = @key;
   end
   ELSE
   begin
      delete from tableB where name_key = @key and cars = @cars;
   end
 
FETCH NEXT FROM del_cur
INTO @key, @cars;
END 
CLOSE del_cur
DEALLOCATE del_cur

Open in new window

0
 
Matt_DuAuthor Commented:
Thanks all!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now