Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using the match and merge statement from sql. It works great between 2 tables, which is what it was originally designed for. However, I am looking to insert data when matched to a third possibly 4th table.

Here is the merge statement:

SQL
Merge into [table1] as T using [table2] as S on T.Last_name = S.Last_name and T.First_name = S.First_name
When matched then update set T.Last_name = S.Last_name, T.First_name = S.First_name;


What I want is to insert the ID and reference column value of all matched rows to table 3. that way I can reference the table by the ID number which is unique.

What I have tried:

I have tried to add another when matched but it does not do anything. Mind you this code is in combination with vb.net code that I am running.
Posted

1 solution

You can use the output clause from the merge statement into a temp table then filter the results and add them into your third table.

Example of Merge Output

-----Inserting data when no match found.
MERGE [dbo].[Department_Target] AS tar
USING [dbo].[Department_Source] AS src
ON tar.[DepartmentID] = src.[DepartmentID]
WHEN NOT MATCHED THEN
   INSERT
   (
      [DepartmentID],
      [Name],
      [GroupName],
      [ModifiedDate]
   )
   VALUES
   (
      src.[DepartmentID], src.[Name], src.[GroupName], src.[ModifiedDate]
   )
OUTPUT
   $action,
   inserted.*,
   deleted.*;
 
Share this answer
 
Comments
Member 11856456 11-Jul-18 13:31pm    
I see that the code is using the source information for the insert, but where is it being sent to for the output? Can I specify a table for the out put and can I do this on a when matched statement?
Member 13896879 12-Jul-18 3:15am    
The output from the merge statement will be rows that have been inserted or deleted. The way does updates or for these purposes, matches will be to delete the row then insert the same row with the updated value maintaining the primary key values. Also worth noting the $action will denote what action was taken on the row sop INSERT, UPDATE or DELETE.

Below is some more information on the $action column. Hopefully this will help you sift the results so you can commit them to your third table

$action
Is available only for the MERGE statement. Specifies a column of type nvarchar(10) in the OUTPUT clause in a MERGE statement that returns one of three values for each row: 'INSERT', 'UPDATE', or 'DELETE', according to the action that was performed on that row.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900