Skip to content
Advertisement

TSQL – Union records based on partial uniqueness

Sample Data

Currently inserted data:

Goal: To insert record into the table variable (or cte/temp table) based on uniqueness ONLY ON [Id] field. “UNION” would not do that because, at minimum, [Group] is going to make duplicate records based on just [Id]… unique. Oh, and [Group] value basically indicates the level of importance, 1 = these records should be inserted first and 3 = these records should be inserted last, after making sure there are no other records in the target table with same [Id] value.

Expected to insert data:

I can do this by first inserting [Group] = 1 records into @T1. Then write another insert for [Group] = 2 where [Id] doesn’t exist, and so on. But am looking for an efficient way. I want to make the insert efficient.

Advertisement

Answer

First create a CTE with all the rows that you want to insert:

and then in the INSERT statement you can use NOT EXISTS:

See the demo.

Or ROW_NUMBER() window function:

See the demo.
Results:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement