创建DML触发器(用于删除)

时间:2016-01-31 17:03:01

标签: sql-server tsql triggers

我的数据库中有四个表:产品,打印机,PC,笔记本电脑。 在所有这些表格中,我都有属性"模型"。所有型号的产品包括:打印机,PC和笔记本电脑。我需要创建一个触发器来阻止删除价格> 300的模型,这个模型由" A"制造商。

select distinct 
    products.model 
from 
    products 
left join 
    PC on products.model = PC.model
left join 
    laptops on products.model = laptops.model
left join 
    printers on products.model = printers.model 
where 
    manufacturer = 'A' 
    and (PC.price > 300 or laptops.price > 300 or printers.price > 300);

SELECT返回满足此条件的模型。我试图创建一个DML触发器。 的 [1]

CREATE TRIGGER TASK3 
ON products  
FOR DELETE
AS
   IF ((SELECT deleted.model FROM deleted) 
       IN (select products.model 
           from products 
           left join PC on products.model = PC.model
           left join laptops on products.model = laptops.model
           left join printers on products.model = printers.model 
           where manufacturer = 'A' 
             and (PC.price > 300 or laptops.price > 300 or printers.price > 300))) 
    begin
        raiserror ( 'This model can't be deleted, because price is greater than 300 and manufacturer is 'A',2,1)
        rollback transaction;
    end
    else 
         print 'That model will be deleted'

我尝试将要删除的属性值(来自已删除的表)与SELECT返回的值进行比较,如 [1] ,以防如果在尊重的模型列表中满足该值这个条件(价格>&&制造商=' A')然后是触发器来阻止他的删除。

1 个答案:

答案 0 :(得分:1)

请注意,在SQL Server中,删除可能会影响多个记录。因此,您的第一个子查询可能会导致返回太多记录的问题。

如果你想在一条记录失败时阻止执行整个delete,那么:

if (exists (select 1
            from deleted d
            where d.manufacturer = 'A' and
                  (exists (select 1 from pc p where p.model = d.model and p.price > 300) or
                   exists (select 1 from laptops l where l.model = d.model and l.price > 300) or
                   exists (select 1 from printers p where p.model = d.model and p.price > 300)
                  )
          )
    )
begin
    raiseerror . . .
end;
   )