· 7 years ago · Sep 07, 2018, 12:32 PM
1SQL delete from a table where a value is true in other table
2delete from a where aa = 100 and exists (select * from b where bb = 7);
3
4create table A (AA int)
5create table B (BB int)
6
7insert into A values (100)
8insert into B values (1)
9
10--Invalid Case
11if exists (select 1 from B where BB = 7)
12begin
13 delete from A where aa = 100
14 if @@rowcount > 0
15 begin
16 print 'BB in B has value euqal to 7'
17 end
18end
19else
20 begin
21 print 'BB in B not equals to 7'
22 end
23
24--Valid Case
25update B set BB = 7
26if exists (select 1 from B where BB = 7)
27begin
28 delete from A where aa = 100
29 if @@rowcount > 0
30 begin
31 print 'BB in B has value euqal to 7'
32 end
33end
34else
35 begin
36 print 'BB in B not equals to 7 and Data Deleted from A'
37 end