触发以防止sql树中的无限循环

时间:2009-06-13 09:44:21

标签: sql tree loops triggers

我有节点表(NodeId,NodeName)和结构表(ParentNodeId,ChildNodeId)。如何编写一个触发器来检查插入更新或删除语句是否会导致无限关系?

2 个答案:

答案 0 :(得分:3)

这是我的解决方案,到目前为止它按预期工作。

CREATE TRIGGER [dbo].[CheckNodeDependence] ON [dbo].[ObjectTrees]
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @CTable TABLE(ChildId INT NOT NULL,
                          ParentId INT NOT NULL,
                          [Level] INT NOT NULL,
                          RowId INT NOT NULL)

    DECLARE @Level INT
    SET @Level = 1

    DECLARE @rows_affected INT
    SET @rows_affected = 1

    INSERT INTO @CTable
    SELECT ObjectId, ParentId, 1, ObjectId FROM INSERTED

    WHILE @rows_affected > 0
    BEGIN
        SET @Level = @Level + 1
        INSERT INTO @CTable
        SELECT T.ObjectId, T.ParentId, @Level, C.RowId
            FROM ObjectTrees T
                INNER JOIN @CTable C ON T.ParentId = C.ChildId
                AND C.Level = @Level - 1

            SET @rows_affected = @@rowcount
            IF EXISTS(
                SELECT * FROM @CTable B
                    INNER JOIN @CTable V ON B.level = 1
                    AND V.Level > 1
                    AND V.RowId = B.RowId
                    AND V.ChildId = B.RowId)
            BEGIN
                    DECLARE @error_message VARCHAR(200)
                    SET @error_message = 'Operation would cause illegal circular reference in tree structure, level = ' + CAST(@Level AS VARCHAR(30))
                    RAISERROR(@error_message,16,1)
                    ROLLBACK TRANSACTION
                    RETURN
            END
        END
    END
GO

答案 1 :(得分:1)

您必须以递归方式检查父项不会直接或间接成为其子项的子项的循环依赖条件。

在SQL Server 2005中,您可以为其编写递归CTE。一个例子 -

WITH [RecursiveCTE]([Id], [ParentAccountId]) AS
(
    SELECT
        [Id],
        [ParentAccountId]
    FROM [Structure]
    WHERE [Id] = @Id
    UNION ALL
    SELECT
        S.[Id],
        S.[ParentAccountId]
    FROM [Structure] S INNER JOIN [RecursiveCTE] RCTE ON S.[ParentAccountId] = RCTE.[Id]
)
SELECT * FROM [RecursiveCTE]