使用触发器根据条件锁定某些行

时间:2012-02-20 12:34:45

标签: tsql

例如,假设有一个包含某些行的表,如何根据等于true的条件阻止对某些行的更新,但允许更新在条件为false的所有行上提交。

举个例子,我通过中止整个交易“锁定”1/4/2007之前的所有行

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

如果要执行以下操作:

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.

有没有办法修改此触发器以允许事务提交,但只有日期为&gt;的行? 2007年1月4日

这是一个非常简短的例子(我正在使用的表格要复杂得多),如果我诚实,我认为如果整个交易失败,它会更清晰,我只是好奇它是如何做到的。

1 个答案:

答案 0 :(得分:3)

您需要BEFORE aka INSTEAD OF trigger并过滤仅允许行。

未测试:

CREATE TRIGGER [dbo].[LockOldWelshRows] ON [dbo].[tbl_TriggerTest]
    INSTEAD OF UPDATE
AS
    BEGIN

      UPDATE 
         T
      SET 
         T.SomeCol = I.SomeCol...
      FROM
         [dbo].[tbl_TriggerTest] T
         JOIN 
         INSERTED I ON T.keycol = I.keycol 
      WHERE
         T.[Date] >= '20070401';

    END

GO