说我有一个自我关系表如下:
ID - Name - ParentID
现在,每当用户在此表中插入某些内容时,我想检查插入的名称是否已经在
ParentID
等于插入的行,如果为true,则回滚事务。
但问题是,当我从插入的表中检查带有parentID
的行时,插入的行也已经在主表中。因此,触发器始终回滚事务。
这是我的触发器:
ALTER TRIGGER TG_Check_Existance_In_myTbl
ON myTbl FOR INSERT,UPDATE AS
DEClARE @result BIT
DECLARE @numberOfRows INT
DECLARE @counter INT
DECLARE @names nVARCHAR (30)
DECLARE @name NVARCHAR (30)
SET @result = 0
SET @numberOfRows = (SELECT COUNT (Name)
FROM myTbl
WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SET @counter = 1;
SELECT @name = Name
FROM inserted
WHILE (@counter <= @numberOfRows)
BEGIN
WITH Q
AS
(
SELECT ROW_NUMBER()
OVER (ORDER BY Name) 'Row', Name
FROM myTbl WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SELECT @names = Name
FROM Q
WHERE Row = @counter
IF @name = @names
SET @result=1;
SET @counter = @counter + 1
END
IF @result = 1
ROLLBACK TRAN