Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,

I am working with merge statement to merge two tables but getting error in syntax. Please help me. Thanks in advance.


SQL
MERGE INTO MERGE1 AS M1
USING (SELECT *FROM MERGE2) AS M2 ON
M1.ID=M2.ID
AND M1.NAME=M2.NAME
AND M1.SALARY=M2.SALARY
AND M1.ADDRESS = M2.ADDRESS

WHEN MATCHED THEN
UPDATE
SET M1.ID=M2.ID,
M1.NAME=M2.NAME,
M1.ADDRESS=M2.ADDRESS,
M1.SALARY=M2.SALARY

WHEN NOT MATCHED THEN
INSERT
(ID,NAME,SALARY,ADDRESS)
VALUES (M2.ID,M2.NAME,M2.SALARY,M2.ADDRESS)



Below are the errors.

Error:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'INTO'.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'AS'.
Posted

Make sure that the Merge1 table actually exists and that you are running the query against the right database.

Note that Merge only works with SQL Server 2008 and 2012.
 
Share this answer
 
Comments
bapu_reddy 5-Jan-13 2:03am    
I'm working on SQL server 2008, still getting the same error.
May be the missing brackets around the ON condition?

Try:
SQL
MERGE INTO MERGE1 AS M1
USING (SELECT *FROM MERGE2) AS M2 ON
   (M1.ID=M2.ID
    AND M1.NAME=M2.NAME
    AND M1.SALARY=M2.SALARY
    AND M1.ADDRESS = M2.ADDRESS)
 
WHEN MATCHED THEN
UPDATE
SET M1.ID=M2.ID,
M1.NAME=M2.NAME,
M1.ADDRESS=M2.ADDRESS,
M1.SALARY=M2.SALARY
 
WHEN NOT MATCHED THEN
INSERT
(ID,NAME,SALARY,ADDRESS)
VALUES (M2.ID,M2.NAME,M2.SALARY,M2.ADDRESS)

Refer: MSDN: MERGE (Transact-SQL)[^]
 
Share this answer
 

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