當前位置:首頁 » 編程語言 » sql聯合刪除

sql聯合刪除

發布時間: 2023-06-05 18:17:38

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,所有子表引用的數據就刪除了。

熱點內容
編譯命令cl 發布:2025-09-16 09:57:21 瀏覽:511
小君直播密碼是多少 發布:2025-09-16 09:25:46 瀏覽:600
用中文編譯的編程軟體 發布:2025-09-16 09:04:37 瀏覽:143
語音編譯器教程 發布:2025-09-16 08:57:44 瀏覽:448
sql注冊伺服器 發布:2025-09-16 08:53:17 瀏覽:611
嵌入式linuxc編程入門 發布:2025-09-16 08:24:18 瀏覽:384
碼片編程器 發布:2025-09-16 08:24:08 瀏覽:953
原神各畫質要什麼配置 發布:2025-09-16 08:17:32 瀏覽:321
讀取資料庫生成xml 發布:2025-09-16 08:17:19 瀏覽:798
sql2000開發版 發布:2025-09-16 07:56:31 瀏覽:809