插入触发器的问题(t-sql)

时间:2012-09-20 18:55:05

标签: sql sql-server tsql triggers insert

说我有一个自我关系表如下:

   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

1 个答案:

答案 0 :(得分:1)

除非我遗漏了一些东西,否则你会这么做。

为什么不在两列上使用唯一约束?

table_constraint (Transact-SQL)