我有 3 張這樣的表:
- 表 1:ID、名稱
- 表 2:ID、名稱
- 表 3:Id、EntityName (nvarchar)、EntityId (int)
Table3 上沒有外鍵。我將 Table1 和 Table2 的行插入到 Table3 中,如下所示:
| ID | 物體名稱 | 物體編號 | 其他列 |
|---|---|---|---|
| 1 | 表格1 | 1 | ... |
| 2 | 表2 | 1 | ... |
| 3 | 表2 | 2 | ... |
當我從 Table1 或 Table2 中洗掉一行時,如何從 Table3 級聯它?
uj5u.com熱心網友回復:
您可以delete trigger在每個表上創建一個以從 table3 中洗掉匹配的行,例如:
create trigger Table1Delete on dbo.table1
for delete
as
if @@RowCount = 0 return
set nocount on
delete from t3
from deleted d
join table3 t3 on t3.EntityName='Table1' and d.Id=t3.EntityId
還有一個類似的 Table2
uj5u.com熱心網友回復:
這是您如何撰寫查詢以“模擬”級聯洗掉:
delete from table2 t2
where exists(select 1 from table3
where t2.id = entityId and EntityName = 'Table2')
delete from table1 t1
where exists(select 1 from table3
where t1.id = entityId and EntityName = 'Table1')
如果您有某些條件可以從中洗掉,則table3還應將其包含在這些查詢中。
更新
要自動執行此操作,您需要使用級聯洗掉操作定義外鍵。但是只能在列上定義一個外鍵,因此您需要有兩列 - 一列用于參考table1,第二列用于參考table2。然后在兩者上你都需要定義級聯洗掉。
使用當前的設計(一列參考多個表)這是不可能的,您需要解決(建議在表上實作洗掉觸發器)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/350418.html
標籤:sql-server 查询语句
上一篇:與Pytest模塊的后期系結沖突
