开始使用免费开始使用

触发器 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;
编辑并运行代码