0
說例如,其中一個表具有某些行,如何根據等於true的條件阻止更新某些行,但是允許更新在所有行上提交條件是錯誤的。根據條件使用觸發器鎖定某些行
採取這種例子,我通過中止整個事務
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_TriggerTest] (
[ID] [int] IDENTITY(1,1) NOT NULL,
[Value] [varchar](25) NULL,
[Date] [datetime] NULL,
CONSTRAINT [PK_tbl_TriggerTest] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[tbl_TriggerTest] ON
GO
INSERT [dbo].[tbl_TriggerTest] ([ID], [Value], [Date]) VALUES (1, N'12', CAST(0x0000979A00000000 AS DateTime))
GO
INSERT [dbo].[tbl_TriggerTest] ([ID], [Value], [Date]) VALUES (2, N'13', CAST(0x00009A7500000000 AS DateTime))
GO
INSERT [dbo].[tbl_TriggerTest] ([ID], [Value], [Date]) VALUES (3, N'14', CAST(0x00009BE200000000 AS DateTime))
GO
INSERT [dbo].[tbl_TriggerTest] ([ID], [Value], [Date]) VALUES (4, N'4', CAST(0x00009D4F00000000 AS DateTime))
GO
SET IDENTITY_INSERT [dbo].[tbl_TriggerTest] OFF
GO
CREATE TRIGGER [dbo].[LockOldWelshRows] ON [dbo].[tbl_TriggerTest]
FOR UPDATE
AS
BEGIN
DECLARE @Count INT
SELECT @Count = COUNT([ID])
FROM INSERTED
WHERE [Date] < CONVERT(DATETIME, '01/04/2007 00:00:00', 103)
IF @Count > 0
BEGIN
RAISERROR('Rows prior to 01/04/2007 are locked',16,1)
ROLLBACK TRANSACTION
RETURN ;
END
END
GO
如果一個人「鎖定」之前的所有行到2007年1月4日到運行以下命令:
UPDATE [tbl_TriggerTest] SET [Value] = [Value] + 'M'
交易將失敗,並出現錯誤:
Msg 50000, Level 16, State 1, Procedure LockOldWelshRows, Line 12
Rows prior to 01/04/2007 are locked
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
是否有修改此觸發器以允許交易的方法ñ提交,但只有行日期是> 1/4/2007
這是一個非常簡短的例子(我使用的表格更復雜),如果我是誠實的,我認爲它更清潔如果整個交易失敗了,我只是好奇它是如何完成的。
完美,乾杯 – HeavenCore 2012-02-20 15:11:46
+1 「而不是」 – Pankaj 2012-02-21 08:35:35