我在做練習測試之前,70-461的考試和問題之一是創建表:使列始終包含計算的值,而不觸發
- 有4列,saleid,單價,數量,以及價格。
- 價格通過單位價格和金額的乘積計算得出
- 您不能使用觸發器。
最後一個殺了我。我怎麼能沒有觸發器呢?這裏是我的解決方案,而不是觸發器。
CREATE TABLE [HR].[Stuff](
[saleid] [int] IDENTITY(1,1) NOT NULL,
[unitprice] [float] NOT NULL,
[amount] [float] NOT NULL,
[price] [float] NULL,
)
GO
CREATE TRIGGER [calculate_price_insert]
ON [HR].[Stuff]
INSTEAD OF INSERT
AS
DECLARE @unitprice float = (SELECT TOP 1 unitprice from inserted)
DECLARE @amount float = (SELECT TOP 1 amount from inserted)
INSERT INTO HR.[Stuff]
VALUES(@unitprice,@amount, @unitprice*@amount)
GO
CREATE TRIGGER [calculate_price_update]
ON [HR].[Stuff]
INSTEAD OF UPDATE
AS
DECLARE @unitprice float = (SELECT TOP 1 unitprice from inserted)
DECLARE @amount float = (SELECT TOP 1 amount from inserted)
UPDATE HR.[Stuff]
SET unitprice = @unitprice, amount = @amount, price = @unitprice*@amount
WHERE unitprice = (SELECT TOP 1 saleid from inserted)
GO
爲什麼不創建一個視圖? – jarlh
因爲這是任務,要創建一個這樣的表=] – Skylerdw