在SQL Server中有两个表:Invoices
(InvoiceId,Number,Date,Customer,TotalValue)和InvoicesElements
(InvoiceId,Good,Qty,Value)。
每个交易都会在Invoices
中插入一行,在InvoicesElements
中插入一行/多行。
我需要在Invoices
表上设置一个触发器,当Good
表中的InvoicesElements
为'Bike'且客户为'ABC'时,该触发器将引发错误和回滚事务。
任何帮助都非常感激。
Przemek
答案 0 :(得分:0)
ALTER TABLE
InvoicesElements
ADD CONSTRAINT
CHK_GOOD
CHECK (good <> 'Bike' OR good IS NULL)
更新
CREATE TRIGGER
TR_InvoicesElements_AIU
ON InvoicesElements
AFTER INSERT, UPDATE
AS
IF EXISTS
(
SELECT NULL
FROM INSERTED ie
JOIN Invoices inv
ON inv.id = ie.invoiceId
WHERE ie.good = 'bike'
AND inv.customer = 'ABC'
)
THROW 50000, 'Not sure why but you cannot sell bikes to ABC', 0
GO
CREATE TRIGGER
TR_Invoices_AIU
ON Invoices
AFTER INSERT, UPDATE
AS
IF EXISTS
(
SELECT NULL
FROM InvoiceElements ie
JOIN INSERTED inv
ON inv.id = ie.invoiceId
WHERE ie.good = 'bike'
AND inv.customer = 'ABC'
)
THROW 50000, 'Not sure why but you cannot sell bikes to ABC', 0
GO