3

这里我有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

……

而且我不知道如何完成这些代码,希望大家能帮助我,谢谢。

4

3 回答 3

1

您不必将TotalPrice存储在BookInvoice 表中,因为您可以使用其他表中的值得出该值。

select Book.Price * BookOrder.Quantity as TotalPrice 
from Book 
join BookOrder
on BookOrder.BookId=Book.id
于 2012-11-14T11:43:15.873 回答
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
于 2012-11-14T11:40:13.280 回答
0

如果您必须使用触发器,则需要创建触发器以涵盖所有情况。例如,更新表 BookInvoice 以防一本书的 UnitPrice 发生变化。或者即使表 BookOrder 等中的 Quantity 发生变化。

而不是使用触发器,您应该可能使用立即计算您想要的值的视图。就像是:

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
于 2012-11-14T11:49:00.243 回答