触发器 vs. 计算列
在继续分析数据库时,您又发现了两个有趣的对象:
表
SalesWithPrice有一列通过Quantity * Price计算TotalAmount。这是使用计算列完成的,计算所用的列都来自同一张表。在表
SalesWithoutPrice上创建了触发器SalesCalculateTotalAmount。由于SalesWithoutPrice表中没有Price列,因此无法用计算列来得到TotalAmount。该触发器通过引用Products表中的Price列来克服这一限制。
本练习是课程的一部分
在 SQL Server 中构建与优化触发器
交互式实操练习
通过完成这段示例代码来试试这个练习。
-- Add the following rows to the table
INSERT INTO ___ (Customer, Product, Price, Currency, Quantity)
VALUES ('Fruit Mag', 'Pomelo', 1.12, 'USD', 200),
('VitaFruit', 'Avocado', 2.67, 'USD', 400),
('Tasty Fruits', 'Blackcurrant', 2.32, 'USD', 1100),
('Health Mag', 'Kiwi', 1.42, 'USD', 100),
('eShop', 'Plum', 1.1, 'USD', 500);
-- Verify the results after adding the new rows
SELECT * FROM SalesWithPrice;