0

假设我有一个自关系表,如下所示:

   ID - Name - ParentID

现在每次用户在此表中插入某事时,我想检查插入的名称是否已经在ParentID等于插入的行中,如果为真则回滚事务。

但问题是当我检查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
4

1 回答 1

1

除非我遗漏了一些东西,否则你这样做太难了。

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

table_constraint (Transact-SQL)

于 2012-09-20T19:25:17.347 回答