触发器应该对从表中删除行做出反应如果表中有一些耗材,则来自该供应商的耗材,触发器应取消删除。 此代码允许删除供应商和供应商的供应商:
CREATE TRIGGER SuppliersDeleteCondition
ON Suppliers
FOR DELETE
AS
IF EXISTS (
SELECT 1
FROM Supplies Ses
JOIN DELETED D
ON D.SupplierID=Ses.SupplierID
)
BEGIN
RAISERROR ('This supplier has some supplies', 16, 1)
ROLLBACK TRANSACTION
END;
大约表格视图是:
供应商(供应商ID,名称,地址,银行详细信息),供应(SupplyID,SupplierID,ProductID,ImplementationPeriod,重量,价格)
这是CREATE TABLE:
CREATE TABLE Suppliers
(
SupplierID INT IDENTITY,
Name VARCHAR(150) NOT NULL UNIQUE,
Address VARCHAR(900) NOT NULL,
BankDetails VARCHAR(9) NOT NULL UNIQUE,
CONSTRAINT pk_SupplierID PRIMARY KEY (SupplierID),
CONSTRAINT chk_Name_Suppliers CHECK (NOT Name LIKE '%[^a-z ]%' AND NOT Name LIKE '[ ]%' AND NOT Name LIKE '%[ ]' AND NOT Name LIKE '%[ ][ ]%'),
CONSTRAINT chk_Address_Suppliers CHECK (NOT Address LIKE '%[^a-zA-z0-9,./ ]%' AND NOT Address LIKE '[ ]%'),
CONSTRAINT chk_BankDetails_Suppliers CHECK (BankDetails LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
);
CREATE TABLE Supplies
(
SupplyID INT IDENTITY,
SupplierID INT,
ProductID INT,
ImplementationPeriod DATE NOT NULL,
Weight REAL NOT NULL,
Price MONEY NOT NULL,
CONSTRAINT pk_SupplyID PRIMARY KEY (SupplyID),
CONSTRAINT fk_SupplierID FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID) ON DELETE CASCADE,
CONSTRAINT fk_ProductID FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE CASCADE,
CONSTRAINT chk_Weight_Supplies CHECK (Weight > 0)
);
当我删除这样的行时:
DELETE FROM Suppliers WHERE SupplierID=18
此行已删除,我没有错误
答案 0 :(得分:3)
您有一个带有DELETE CASCADE
选项的外键,因此删除触发器是多余的。在供应商和耗材的行被删除后,AFTER DELETE
触发器将触发,因此任何行都不会符合EXISTS
谓词的条件。除非您可以删除外键,否则不需要触发器,我不建议这样做。让SQL Server为您完成工作。