Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I am using sql 2008 r2. when i use merge statement i am gettig error when i execute following code:

merge products as trgt
using updatedproducts as src 
      on (trgt.productid = src.productid) 
when matched and trgt.productname <> src.productname or trgt.rate <> src.rate then 
     update set trgt.productname = src.productname, 
     trgt.rate = src.rate 
when not matched by trgt then 
     insert (productid, productname, rate) values (src.productid, src.productname, src.rate)
when not matched by src then 
     delete output $action, 
     deleted.productid as trgtproductid, 
     deleted.productname as trgtproductname, 
     deleted.rate as trgtrate, 
     inserted.productid as srcproductid, 
     inserted.productname as srcproductname, 
     inserted.rate as srcrate; 

select @@rowcount;
go

I am getting error like this:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'as'.

Why am i getting this error?

share|improve this question

2 Answers 2

Try using the keywords TARGET and SOURCE.

MERGE products AS target
  USING updatedproducts AS source
  ON (target.productid = source.productid)
  WHEN MATCHED and target.productname <> source.productname OR
    target.rate <> source.rate
    THEN UPDATE
     SET
      target.productname = source.productname
     ,target.rate = source.rate
  WHEN NOT MATCHED BY TARGET 
    THEN INSERT
      (productid
      ,productname
      ,rate)
     VALUES
      (source.productid
      ,source.productname
      ,source.rate)
  WHEN NOT MATCHED BY SOURCE 
    THEN DELETE
  OUTPUT
    $action
   ,deleted.productid AS trgtproductid
   ,deleted.productname AS trgtproductname
   ,deleted.rate AS trgtrate
   ,inserted.productid AS srcproductid
   ,inserted.productname AS srcproductname
   ,inserted.rate AS srcrate;
SELECT
  @@rowcount;

Should work like a charm

share|improve this answer

if you use when not matched by SOURCE/TARGET , SOURCE and TARGET are not aliases, but parts of merge syntax.

For instance, when not matched by src then ... is incorrect, it has to be when not matched by SOURCE then... The same for when not matched by trg (should be by TARGET or just WHEN NOT MATCHED).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.