而不是在具有多个表的SQL Server中删除触发器

时间:2015-04-06 17:36:06

标签: sql sql-server join triggers

我正在尝试在SQL Server中创建一个而不是删除触发器,它将在从第一个表中删除项目之前检查第二个表中项目的值/数量。我无法在表之间创建连接。任何人都可以识别我的代码有什么问题吗?我很感激任何帮助。

CREATE TRIGGER  tr_delete_orders
ON orders
INSTEAD OF DELETE
AS
   DECLARE @del_qty INT

   SET @del_qty = orders.order_id
   FROM DELETED
   JOIN order_details ON order_details.order_id=orders.order_id

   IF (SELECT order_details.quantity FROM DELETED) >= 1
   BEGIN
        PRINT   'You may not delete items that have quantity in the order_detail table.'
        ROLLBACK TRANSACTION
   END;

1 个答案:

答案 0 :(得分:0)

我猜您只想删除不包含任何订单明细的订单(数量= 0)。即使您计划每个订单使用删除功能,触发器也应该能够删除许多订单(如上面的注释中所指出的)。

CREATE TRIGGER  tr_delete_orders
ON orders
INSTEAD OF DELETE
AS
   delete o 
   from orders o inner join deleted d on d.order_id = o.order_id
   where not exists (select top 1 
                     from order_details od 
                     where od.order_id = o.order_id and od.quantity > 0)