我建議你使用一個而不是觸發器來減少寫入表的次數。在觸發器中使用更新將導致刪除,然後導致插入,因此總共對錶執行三個操作。使用INSTEAD OF觸發器會招致只需一個人操作
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BaseTable]') AND type in (N'U'))
DROP TABLE [dbo].[BaseTable]
GO
CREATE TABLE BaseTable
(BaseTableID int PRIMARY KEY IDENTITY(1,1),
[email protected] int,
QYear int,
SUID int,
units int,
Grade int
)
GO
--Create an INSTEAD OF INSERT trigger on the table.
CREATE TRIGGER InsteadTrigger on BaseTable
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO BaseTable
SELECT
[email protected] ,
QYear ,
SUID ,
units ,
CASE
WHEN Grade > 20 THEN 3
ELSE Grade
END
FROM inserted
END
GO
INSERT INTO [deleteme].[dbo].[BaseTable]
([[email protected]]
,[QYear]
,[SUID]
,[units]
,[Grade])
VALUES
(10
,10
,10
,10
,10)
Select * from BaseTable
INSERT INTO [deleteme].[dbo].[BaseTable]
([[email protected]]
,[QYear]
,[SUID]
,[units]
,[Grade])
VALUES
(20
,20
,20
,20
,20)
Select * from BaseTable
INSERT INTO [deleteme].[dbo].[BaseTable]
([[email protected]]
,[QYear]
,[SUID]
,[units]
,[Grade])
VALUES
(30
,30
,30
,30
,30),
(40
,40
,40
,40
,40),
(50
,50
,50
,50
,50)
Select * from BaseTable
BaseTableID [email protected] QYear SUID units Grade
1 10 10 10 10 10
2 20 20 20 20 20
3 30 30 30 30 3
4 40 40 40 40 3
5 50 50 50 50 3
你想創建一個檢查約束或觸發器嗎?檢查約束將驗證輸入的值,而觸發器可以做到更多。儘管如此,檢查約束最有可能是進行驗證的最佳位置。 – 2011-06-02 14:48:13