在两个表之间计算的触发器SQL

时间:2015-01-02 13:48:12

标签: sql sql-server triggers

我有两个表PRODUCTINVOICE

Create table PRODUCT(){
    PRODUCTID nvarchar(10), -- product id
    PRICE float,
}
Create table INVOICE(){
    PRODUCTID nvarchar(10),
    QUANTUM int,
    AMOUNT float,
}

现在我希望在Trigger上创建AMOUNT计算列INVOICEAMOUNT = QUANTUM * PRICE

谢谢你的帮助!

create trigger trig_INVOICE
on INVOICE
after insert, update
as
begin
   declare @price float
   declare @ProductId nvarchar(10)
   set @ProductID = (Select PRODUCTID from INVOICE)
   set @price = (Select PRICE from PRODUCT where PRODUCT.PRODUCTID = @ProductId)
   UPDATE INVOICE set AMOUNT = QUANTUM * @price
end

这不起作用-_-

3 个答案:

答案 0 :(得分:0)

InvoiceID表中添加Invoice列作为主键。

INVOICE

上添加触发器
CREATE TRIGGER invoice_trg 
   ON  dbo.INVOICE AFTER INSERT
AS 
BEGIN
    UPDATE INVOICE
    SET    AMOUNT = INVOICE.QUANTUM * PRODUCT.price
    FROM   INVOICE 
    INNER JOIN PRODUCT ON INVOICE.PRODUCTID = PRODUCT.PRODUCTID
    INNER JOIN INSERTED ON INVOICE.PRODUCTID = INSERTED.PRODUCTID

END

答案 1 :(得分:0)

将一个主键添加到Invoice表中,比如说InvID,然后您应该可以使用下面的触发器。

CREATE TRIGGER trig_INVOICE ON INVOICE
AFTER INSERT, UPDATE
AS
BEGIN
    UPDATE  INVOICE
    SET     AMOUNT = QUANTUM * Price
    FROM    inserted ins
            INNER JOIN invoice
            ON InvID = InvID
            INNER JOIN Product
            ON inserted.ProductID = Product.ProductID;
END;/

答案 2 :(得分:0)

不会为每个Row执行触发器。像这样改变你的触发器。

CREATE TRIGGER trig_INVOICE
ON INVOICE
after INSERT, UPDATE
AS
  BEGIN
      UPDATE a
      SET    AMOUNT = QUANTUM * p.price
      FROM   INVOICE a
             JOIN inserted b
               ON a.PRODUCTID = b.PRODUCTID
             JOIN PRODUCT p
               ON a.PRODUCTID = p.PRODUCTID
  END