Search code examples
sql-server-2008-r2sql-merge

SQL Server 2008 R2 : Merge Query


I am using the following syntax for a merge :

MERGE INTO studentinfo as Target
USING StudentInfo_Temp as Source ON Target.Form Number = Source.Form Number

WHEN MATCHED THEN
   UPDATE 
      SET Target.Form Number = Source.Form Number

WHEN NOT MATCHED THEN
   INSERT ([Form Number], [Academic Program]) 
   VALUES (Source.Form Number, Source.Academic Program);

But I am getting an error above on the line

on Target.Form Number = Source.Form Number

If I replace this by Taget.ID = Source.ID it works fine so I am assuming I have to write a column with a space in name some other way.

Any suggestion on the correct syntax?


Solution

  • Use brackets to enclose the values with spaces:

    Target.[Form Number] = Source.[Form Number]
    

    see the section for Delimited identifiers in the documentation for more information.