開始使用免費開始

觸發程序與計算欄位

在持續分析資料庫時,你又發現兩個有趣的物件:

  • 資料表 SalesWithPrice 有一個欄位會將 TotalAmount 計算為 Quantity * Price。這是使用計算欄位完成的,計算時會引用同一張表中的其他欄位。

  • 在 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;
編輯並執行程式碼