我有两个表PRODUCT
和INVOICE
:
Create table PRODUCT(){
PRODUCTID nvarchar(10), -- product id
PRICE float,
}
Create table INVOICE(){
PRODUCTID nvarchar(10),
QUANTUM int,
AMOUNT float,
}
现在我希望在Trigger
上创建AMOUNT
计算列INVOICE
,AMOUNT
= 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
这不起作用-_-
答案 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