SQL DML插入触发器

时间:2017-08-28 00:44:04

标签: sql-server

尝试创建一个dml触发器,在将新数据插入另一个表之前检查列数据是否存在。这是我到目前为止所拥有的

CREATE TRIGGER filter2 ON Sales.CustReviews
AFTER INSERT
AS
IF EXISTS (SELECT *
           FROM Sales.Orders AS so
           JOIN sales.CustReviews AS cr ON so.custid = cr.custid
           WHERE  so.Ordershipped = 'no'
          )  

BEGIN
RAISERROR ('Need to place order before posting review', 16, 1);
ROLLBACK TRANSACTION;
RETURN

END;

GO

INSERT INTO Sales.CustReviews (custid, comment) VALUES ('2', 'this product sucks')

我希望上面的代码失败,因为它没有发送订单,因为默认设置为' no' (sales.order只有1个订单,而custid是1)

1 个答案:

答案 0 :(得分:0)

试试这个:

CREATE TRIGGER filter2 ON Sales.CustReviews
AFTER INSERT
AS
BEGIN
    IF NOT EXISTS (SELECT *
               FROM Sales.Orders AS so
               JOIN sales.CustReviews AS cr ON so.custid = cr.custid
               WHERE so.Ordershipped <> 'no'
              )
        THROW 60000, 'Error Message!', 1;
    RETURN;
END;
GO

BEGIN TRY
    BEGIN TRANSACTION;
    INSERT INTO Sales.CustReviews (custid, comment) VALUES ('2', 'this product sucks');
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
    THROW;
END CATCH;