Trigger to prevent infinite loop in sql tree

I have a node table with (NodeId, NodeName) and a structure table (ParentNodeId, ChildNodeId). How can I write a trigger that checks if the update or delete operator of an insert can cause an infinite relation?

+3
source share
2 answers

Here is my solution, and still it works as expected.

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
+3
source

You will have to recursively check for a circular dependency condition in which the parent does not become a child of its own child, directly or indirectly.

In SQL Server 2005, you can write a recursive CTE for the same. Example -

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]
+1
source

Source: https://habr.com/ru/post/1710396/


All Articles