Using a join in a merge statement

The query you have will give the error

Msg 8156, Level 16, State 1, Line 59 The column ‘AnotherKey’ was
specified multiple times for ‘tmpTable’.

That is because you are using * in the using clause and AnotherKey is part of both table2 and table3.
Specify the columns you need. Also there is no use to have a outer join in there since you are using keycolumn in the onclause.

MERGE table1
USING (SELECT table3.keycolumn,
              table2.DataColumn1,
              table2.DataColumn2
       FROM table2
       INNER JOIN table3
           ON table2.anotherKey = table3.anotherKey
       WHERE table2.anotherKey = 'A1') tmpTable
ON 
   table1.keyColumn = tmpTable.keyColumn
WHEN MATCHED THEN
       UPDATE
       SET table1.DataColumn1 = tmpTable.DataColumn1
            ,table1.DataColumn2 = tmpTable.DataColumn2;

Update

Posting the actual error is always helpful.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ‘a’. Msg 102,
Level 15, State 1, Line 12 Incorrect syntax near ‘d’.

Looks like you are on SQL Server 2005. Merge is avalible from SQL Server 2008.

You can check your SQL Server version with select @@version.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)