Search code examples
t-sqlsql-server-2008triggersslugrecursive-query

Creating Unique URI Slugs - is this a Recursive Trigger? (SQL Server)


Here's my table:

dbo.Posts

  • PostId (IDENTITY, PK)
  • Subject
  • UniqueUri (NVARCHAR(350), NOT NULL)

When i create a "Post", i insert a blank UniqueUri (using the NEWID() built-in function).

I then have a trigger on the "Post" table:

CREATE TRIGGER [dbo].[OnAfterInsertUpdatePostTrigger]
   ON  [dbo].[Posts]
   AFTER INSERT, UPDATE
AS 
BEGIN
    SET NOCOUNT ON

    DECLARE @PostIds IdentityType

    INSERT INTO @PostIds
    SELECT PostId
    FROM INSERTED

    -- Create the UniqueUri's.
    EXECUTE [dbo].[UpdatePostsCleanedUriUniqueUri] @PostIds

END

Which calls a SPROC to create the Unique Uri's.

The SPROC has some code like this:

UPDATE a
    SET a.CleanedUri = NEWID(),
        a.UniqueUri = NEWID()
    FROM [dbo].[Posts] a
        INNER JOIN @PostIds b ON a.PostId = b.Id

I noticed when i tried to insert only a single post, it was taking over a minute.

I can only deduce this is a recursive trigger call?

Basically, when a Post is created/updated, i need to create unique uri's (much like stack, for questions).

The only solution i can think of is created another table called UniqueUri's, which would have nothing but the PostId FK and the Uri, e.g a 1-1, which i always try to avoid.

Then the SPROC would update that table.

Any other suggestions/ideas?


Solution

  • One solution to prevent the trigger recursively firing is to eliminate changes to your columns from the trigger:

    IF ( NOT UPDATE (CleanedUri) AND NOT UPDATE (UniqueUri ) )
    BEGIN
        DECLARE @PostIds IdentityType      
        INSERT INTO @PostIds     
        SELECT PostId     
        FROM INSERTED      
    
        -- Create the UniqueUri's.     
        EXECUTE [dbo].[UpdatePostsCleanedUriUniqueUri] @PostIds 
    END;