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

How to MERGE a subset of the target table?

Asked by Anne Bell Apr 16, 2021 6 views 1 answer
Share

About this question

I am trying 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: It is important to specify only the columns from the target table that are used for matching purposes. That is, specify columns from the target table that are compared to the corresponding column of the source table. Do not attempt to improve query performance by filtering out rows in the target table in the ON clause, such as by specifying AND NOT target_table.column_x = value. Doing so may return unexpected and incorrect results.


but this is exactly what it appears I have to do to make my 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:

CategoryId ItemId ========== ====== 1 1 1 2 1 3 2 1 2 3 3 5 3 6 4 5 What I need to do is to effectively replace all rows in a specific category with a new list of items. My initial attempt to do this looks like this:

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.