这里有3张桌子:
Book [Id] [UnitPrice]
BookOrder [Id] [BookId] [Quantity]
BookInvoice [Id] [OrderId] [TotalPrice]
要求是从Book表中获取UnitPrice,然后是。
UnitPrice * Quantity = TotalPrice
我是SQL的新手,这是我的代码:
CREATE TRIGGER TR_TotalPrice
ON BookInvoice *--Is that correct?*
FOR UPDATE, INSERT
AS
UPDATE BookInvoice SET TotalPrice = Book.Price * BookOrder.Number
FROM Book, BookOrder
...
我不知道如何完成这些代码,希望大家帮助我,谢谢。
答案 0 :(得分:1)
您不必在 BookInvoice 表中存储 TotalPrice ,因为您可以使用其他表中的值派生值。
select Book.Price * BookOrder.Quantity as TotalPrice
from Book
join BookOrder
on BookOrder.BookId=Book.id
答案 1 :(得分:0)
你可以使用触发器
CREATE TRIGGER TR_TotalPrice ON BookInvoice
FOR UPDATE, INSERT
AS
begin
update BookInvoice set
TotalPrice = B.Price * BO.Number
from inserted as i
inner join BookInvoice as BI on BI.Id = i.Id
inner join BookOrder as BO on BO.Id = i.OrderId
inner join Book as B on B.Id = BO.BookId
end
或者您可以使用视图,它会更加规范化,但如果图书Price
发生变化,那么该图书所有发票中的TotalPrice
也会发生变化
create view vw_BookInvoice
as
select
BI.Id,
BI.OrderId,
B.Price * BO.Number as TotalPrice
from BookInvoice as BI
inner join BookOrder as BO on BO.Id = i.OrderId
inner join Book as B on B.Id = BO.BookId
答案 2 :(得分:0)
如果必须使用触发器,则需要创建触发器以涵盖所有情况。例如,如果书的UnitPrice发生更改,则更新表BookInvoice。或者即使表BookOrder等中的数量发生变化
您应该使用可立即计算所需值的视图,而不是使用触发器。类似的东西:
SELECT b.id, bo.id, bo.quantity * b.uniprice TotalPrice
FROM BOOK b, BookOrder BO, BookInvoice BI
WHERE BO.Id = BI.OrderId
AND B.Id = BO.BookId