Skip to content

How to merge Tags in T‐SQL

Edi Wang edited this page Dec 28, 2023 · 1 revision

Example code

DECLARE @SourceTagId     AS INT,
        @TargetTagId     AS INT

SET @SourceTagId = 474
SET @TargetTagId = 179

DECLARE @Temp TABLE (PostId UNIQUEIDENTIFIER)

INSERT INTO @Temp
  (
    PostId
  )(
       SELECT pt.PostId
       FROM   PostTag AS pt
       WHERE  pt.TagId IN (@SourceTagId, @TargetTagId)
       GROUP BY
              pt.PostId
       HAVING COUNT(*) >= 2
   )
------------------------------------------------------------------------------
SELECT 
       p.Title,
       t.DisplayName
FROM   PostTag         AS pt
       INNER JOIN Post      AS p
            ON  p.Id = pt.PostId
       INNER JOIN Tag  AS t
            ON  t.Id = pt.TagId
WHERE  pt.PostId IN (SELECT t.PostId
                     FROM   @Temp t)

-- Step 1. Delete records that will frack up the primary key
DELETE 
FROM   PostTag
WHERE  TagId = @SourceTagId
       AND PostId IN (SELECT t.PostId
                      FROM   @Temp t)

-- Step 2. Update old key to new key
UPDATE PostTag
SET    TagId     = @TargetTagId
WHERE  TagId     = @SourceTagId
Clone this wiki locally