触发引用另一个子元素表

时间:2015-07-02 20:41:18

标签: sql sql-server triggers

在SQL Server中有两个表:Invoices(InvoiceId,Number,Date,Customer,TotalValue)和InvoicesElements(InvoiceId,Good,Qty,Value)。

每个交易都会在Invoices中插入一行,在InvoicesElements中插入一行/多行。

我需要在Invoices表上设置一个触发器,当Good表中的InvoicesElements为'Bike'且客户为'ABC'时,该触发器将引发错误和回滚事务。

任何帮助都非常感激。

Przemek

1 个答案:

答案 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