Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

MERGE in SQL Server - MERGE a subset of the target table

Asked by Ankit Chauhan Apr 22, 2021 5 views 1 answer
Share

About this question

I want to use a MERGE statement to insert or delete rows from a table, but I only want to act on a subset of those rows. The documentation for MERGE has a pretty strongly worded warning:

But this is exactly what it appears I have to do to make my SQL Server MERGE work. The data I have is a standard many-to-many join table of items to categories (e.g. which items are included in which categories) like so:

I need to effectively replace all rows in a specific category with a new list of items. My initial attempt to do this looks like this:

This appears to be working in my tests, but I am doing exactly what MSDN explicitly warns me not to do. This makes me concerned that I will run into unexpected problems later on, but I cannot see any other way to make my MERGE only affect rows with the specific field value (CategoryId = 2) and ignore rows from other categories.

Is there a "more correct" way to achieve this same result? And what are the "unexpected or incorrect results" that MSDN is warning me about?


Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.