MERGE INTO从db2到SQL Server的转换

时间:2017-04-28 14:16:57

标签: sql sql-server merge db2

我正在尝试将此db2查询调整为SQL Server

 MERGE INTO wishlist AS wish USING 
    (SELECT * FROM TABLE (VALUES 
    (?,?,?,?,?,?,?,?,?,?,?,?))) 
    AS new(ID, USER_ID, CONTENT_ID,CONTENT_TYPE, 
    SKU, DATE, TIMESTAMP, VALUE, TITLE, URL, IMAGE_URL, ZONE) 
    ON 
   (wish.content_id = new.content_id and wish.value = new.value and 
   (wish.sku is null or wish.sku = new.sku)) 
WHEN MATCHED THEN UPDATE SET id  = new.id , date = new.date,  timestamp = 
   new.timestamp 
WHEN NOT MATCHED THEN INSERT 
     (ID, USER_ID, CONTENT_ID, CONTENT_TYPE, SKU, DATE, TIMESTAMP, VALUE, 
     TITLE, URL, IMAGE_URL, ZONE) 
     VALUES (new.ID, new.USER_ID, new.CONTENT_ID, 
     new.CONTENT_TYPE, new.SKU, new.DATE, new.TIMESTAMP, new.VALUE, 
     new.TITLE, w.URL, new.IMAGE_URL, new.ZONE)

我想出的是:

MERGE INTO wishlist AS wish 
USING
    (  SELECT  * FROM (VALUES 
    (?,?,?,?,?,?,?,?,?,?,?,?))
AS new(ID, USER_ID, CONTENT_ID, CONTENT_TYPE, SKU, DATE, TIMESTAMP, VALUE, 
TITLE, URL, IMAGE_URL, ZONE) 
ON
([wish].[content_id] = [new].[content_id] and [wish].[value] = [new].[value] 
and ([wish].[sku] is null or [wish].[sku] = [new].[sku]))
WHEN MATCHED THEN 
UPDATE SET id = new.id , date = new.date,  timestamp = new.timestamp 
WHEN NOT MATCHED THEN 
INSERT (ID, USER_ID, CONTENT_ID, CONTENT_TYPE, SKU, DATE, TIMESTAMP, VALUE, 
TITLE, URL, IMAGE_URL, ZONE) VALUES (new.ID, new.USER_ID, new.CONTENT_ID, 
new.CONTENT_TYPE, new.SKU, new.DATE, new.TIMESTAMP, new.VALUE, new.TITLE, 
new.URL, new.IMAGE_URL, new.ZONE)

在我看来,最后一个版本尊重文档https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql中的语法,但我仍然得到:

Incorrect syntax near the keyword 'ON'.

1 个答案:

答案 0 :(得分:1)

using()的括号错误,我还将您的别名从wish换成targetnew换成src

merge into wishlist as target
using (
 select *
 from (
  values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )) 
   as new(ID, USER_ID, CONTENT_ID, CONTENT_TYPE, SKU, date, timestamp, VALUE, TITLE, URL, IMAGE_URL, ZONE)
  ) as src /* <--- added `) as src` to end using() */
   on [target].[content_id] = [src].[content_id] 
  and [target].[value] = [src].[value] 
  and ([target].[sku] is null or [target].[sku] = [src].[sku])
  WHEN matched THEN
    update
      set id = src.id
        , date = src.date
        , timestamp = src.timestamp 
  WHEN not matched THEN
  insert (ID, USER_ID, CONTENT_ID, CONTENT_TYPE, SKU, date, timestamp, VALUE, TITLE, URL, IMAGE_URL, ZONE ) 
  values (src.ID, src.USER_ID, src.CONTENT_ID, src.CONTENT_TYPE, src.SKU, src.date, src.timestamp, src.VALUE, src.TITLE, src.URL, src.IMAGE_URL, src.ZONE ) 
  --) /* <-- doesn't go here */