简体   繁体   中英

Merge Query in DB2

I need to update few columns in one table with the very convoluted calculation.

I'm not good enough in SQL so I tried to use "with" clause in combination with update, but It threw error.

Then I found a post online which suggested to use MERGE so I came up with Merge query. But that one was also throwing an error.

So I removed all other column and updating only one column to remove complexity, but no avail still errors

Below is my query, select query inside working perfectly fine. Please suggest.

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

Error is

An error occurred when executing the SQL command: MERGE INTO ........

DB2 SQL Error: SQLCODE=-199, SQLSTATE=42601, SQLERRMC=SELECT;VALUES, DRIVER=3.61.75 [SQL State=42601, DB Errorcode=-199]

Try this instead, I think you forgot your identifier in your select statement because after the "ON" statement "CORRECT.Primary_ID" doesn't associate to anything.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM