我有一个表tblDHColl,其中包含ProjectID,HoleID,X,Y,Z和Locked(位数据类型)字段。我想创建一个触发器来阻止任何更新或删除Locked = 1或' True'的洞。如果Locked字段为0或“false”,则我希望允许对数据进行任何其他更新或删除操作。任何洞。 由于我是触发器的新手,请告诉我如何在tblDHColl上创建触发器。
CREATE TRIGGER [dbo].[TR_utblDHCollRollBack] ON [dbo].[tblDHColl]
FOR UPDATE, DELETE
AS
IF EXISTS
(
SELECT *
FROM deleted d
INNER JOIN tbldhcoll c ON d.DataSet = c.DataSet AND d.Hole_ID = c.Hole_ID
where locked=1
) AND EXISTS
(
SELECT *
FROM inserted i
INNER JOIN tbldhcoll c ON i.DataSet = c.DataSet AND i.Hole_ID = c.Hole_ID
where locked=1
)
BEGIN
RAISERROR('ERROR: Validated data cannot be modified',16,-1)
ROLLBACK TRANSACTION
RETURN
END
GO
ALTER TABLE [dbo].[tblDHColl] ENABLE TRIGGER [TR_utblDHCollRollBack] GO
亲切的问候, 迪内希
答案 0 :(得分:0)
如果要更改删除或更新记录的逻辑,则应使用“代替”触发器。它会是这样的:
CREATE TRIGGER [dbo].[TR_utblDHCollRollBack] ON [dbo].[tblDHColl]
INSTEAD OF UPDATE, DELETE
AS
IF TRIGGER_NESTLEVEL() > 1 RETURN
DECLARE @Count INT
SELECT @Count = COUNT(*) FROM inserted
IF @Count > 0 -- This is UPDATE
BEGIN
UPDATE c
SET
Field1 = i.Field1,
Field2 = i.Field2,
/*
.
.
.
*/
FieldN = i.FieldN
FROM deleted d
INNER JOIN inserted i ON i.Hole_ID = d.Hole_ID
INNER JOIN tbldhcoll c ON d.DataSet = c.DataSet AND d.Hole_ID = c.Hole_ID
where ISNULL(d.locked, 0) != 1
END
ELSE
BEGIN
DELETE c
FROM deleted d
INNER JOIN tbldhcoll c ON d.DataSet = c.DataSet AND d.Hole_ID = c.Hole_ID
where ISNULL(d.locked, 0) != 1
END
GO