sql聯合刪除
Ⅰ sql 語句刪除問題同時刪除兩個表內關聯的數據
一個sql語句是沒辦法執行兩個刪除操作,如果你要實現上面的功能,有以下幾個選擇:
1.用外鍵關聯刪除,把B表的uid設成外鍵關聯A表的ID,並關聯刪除操作
2.用存儲過程,用事務來處理實現;
望採納!
Ⅱ SQL sever中要刪除兩個相關聯的表該怎麼進行級聯刪除
------解決方案-------------------------------------------------------- --1、建立一個觸發器(推薦)
create trigger on p for deleteas �0�2delete from spj where pno = (select pno from deleted)go--執行刪除delete from p where pname='螺絲'
--2、級聯刪除
alter table p add constraint pk_p_id primary key (pno)go--為tb創建外健,並指定級聯刪除
alter table spj add constraint fk_spj_aid foreign key (pno) references p(pno) on delete cascadego------解決方案----------------------------------------------------------推薦觸發器控制,可控性比較強
SQL code --1、建立一個觸發器(推薦) create trigger on p for delete as delete from spj where pno = (select pno from deleted) go --執行刪除 delete from p where pname='螺絲' --2、級聯刪除 alter table p add constraint pk_p_id primary key (pno) go --為tb創建外健,並指定級聯刪除 alter table spj add constraint fk_spj_aid foreign key (pno) references p(pno) on delete cascade go
------解決方案--------------------------------------------------------建立測試數據
SQL code if object_id('dbo.SPJ') is not null drop table dbo.SPJ; go if object_id('dbo.P') is not null drop table dbo.P; go create table dbo.P ( pno int not null primary key, pname nvarchar(20) not null ); go create table dbo.SPJ ( sno int not null primary key, pno int not null ); insert into dbo.P select 1, 'type-a' union all select 2, 'type-b' union all select 3, 'type-c'; go insert into dbo.SPJ select 1, 1 union all select 2, 1 union all select 3, 1 union all select 4, 2 union all select 5, 3 union all select 6, 3; go
------解決方案--------------------------------------------------------建議用外鍵約束
先刪除子表在刪除父表
------解決方案-------------------------------------------------------- �0�2個人建議用事務處理。
Ⅲ SQL 如何把兩個表相關聯的數據一同刪除
其實你這個問題最好用資料庫本身的外鍵解決。就是在子表建立指向父表的外鍵。當刪除主表數據時,只要加上delete語句加上 on cascade,所有子表引用的數據就刪除了。