Syntax

當我使用合併語句時出現錯誤

  • April 15, 2013

我正在使用 sql 2008 r2。當我使用合併語句時,當我執行以下程式碼時出現 gettig 錯誤:

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

我收到這樣的錯誤:

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

為什麼我會收到此錯誤?

嘗試使用關鍵字 TARGET 和 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;

應該像魅力一樣工作

如果您使用when not matched by SOURCE/TARGET,SOURCE並且TARGET不是別名,而是merge語法的一部分。

例如,when not matched by src then ...是不正確的,它必須是when not matched by SOURCE then...相同的when not matched by trg(應該是 by TARGET或只是WHEN NOT MATCHED)。

引用自:https://dba.stackexchange.com/questions/39995