在DB2中合并查询

时间:2015-05-12 16:57:19

标签: sql merge sql-update db2

我需要使用非常复杂的计算更新一个表中的几列。

我在SQL中不够好,所以我尝试将“with”子句与更新结合使用,但它引发了错误。

然后我在网上发现了一条建议使用MERGE的帖子,所以我提出了Merge查询。但那个人也犯了一个错误。

因此,我删除了所有其他列并仅更新了一列以消除复杂性,但仍无法使用错误

下面是我的查询,选择查询内部工作完全正常。 请建议。

MERGE INTO TABLE_1 AS O 
USING (
SELECT  ((TO_NUMBER(TABLE_3.Total_Whsle_Price)-TO_NUMBER(TABLE_2.OPT_BASE_WHSLE)) - ((TO_NUMBER(TABLE_3.Total_Whsle_Price)-TO_NUMBER(TABLE_2.OPT_BASE_WHSLE))*TO_NUMBER(TABLE_1.AUC_MILEAGE))/100000 ) as CORRECT_FLOOR_PRICE
FROM TABLE_1, TABLE_2,TABLE_3
WHERE TABLE_2.Primary_ID= TABLE_1.Primary_ID
AND TABLE_2.option_code = 'FSDS'
AND TABLE_1.FLOOR_PRICE <> '0.00'   
and TABLE_3.Primary_ID=TABLE_1.Primary_ID
and TABLE_3.Primary_ID=TABLE_2.Primary_ID
) AS CORRECT
ON(
 O.Primary_ID = CORRECT.Primary_ID 
)
WHEN MATCHED THEN
UPDATE 
set O.FLOOR_PRICE =CORRECT.CORRECT_FLOOR_PRICE

错误是

  

执行SQL命令时发生错误:      MERGE INTO ........

     

DB2 SQL错误:SQLCODE = -199,SQLSTATE = 42601,SQLERRMC = SELECT; VALUES,DRIVER = 3.61.75 [SQL状态= 42601,DB错误代码= -199]

1 个答案:

答案 0 :(得分:0)

请尝试这样做,我认为您在select语句中忘记了您的标识符,因为在“ON”语句“CORRECT.Primary_ID”之后没有任何关联。

MERGE INTO TABLE_1 as O 
USING (
  SELECT  ((TO_NUMBER(TABLE_3.Total_Whsle_Price)-TO_NUMBER
    (TABLE_2.OPT_BASE_WHSLE)) - ((TO_NUMBER(TABLE_3.Total_Whsle_Price)
    -TO_NUMBER(TABLE_2.OPT_BASE_WHSLE))*TO_NUMBER
    (TABLE_1.AUC_MILEAGE))/100000 ) as CORRECT_FLOOR_PRICE,
    TABLE_1.Primary_ID AS Primary_ID 
  FROM 
    TABLE_1, TABLE_2,TABLE_3
    WHERE TABLE_2.Primary_ID = TABLE_1.Primary_ID
    AND TABLE_2.option_code = 'FSDS'
    AND TABLE_1.FLOOR_PRICE <> '0.00'   
    AND TABLE_3.Primary_ID=TABLE_1.Primary_ID
    AND TABLE_3.Primary_ID=TABLE_2.Primary_ID
) AS CORRECT
ON(
 O.Primary_ID = CORRECT.Primary_ID 
)
WHEN MATCHED THEN
UPDATE 
set O.FLOOR_PRICE = CORRECT.CORRECT_FLOOR_PRICE