I have a table with 3 columns (ID, NAME, DESCRIPTION). 'ID' is the PRIMARY key. As the following query in MySQL to insert/update two rows, I want to write a query for DB2 database table.
INSERT INTO <Table name> (ID, NAME, DESCRIPTION) VALUES(?, ?, ?), (?, ?, ?)
ON DUPLICATE KEY UPDATE NAME = VALUES(NAME), DESCRIPTION = VALUES(DESCRIPTION);
I tried to modify the following MERGE INTO query to insert/update two rows into the table in DB2 database, but I failed.
MERGE INTO <Table name> USING "SYSIBM".DUAL ON (ID= ?)
WHEN MATCHED THEN UPDATE SET NAME= ? , DESCRIPTION= ?
WHEN NOT MATCHED THEN INSERT (ID,NAME,DESCRIPTION) VALUES (?, ?, ?);
How can I do this?
Try this:
--#SET TERMINATOR @
DECLARE GLOBAL TEMPORARY TABLE SESSION.MYTAB (ID INT, NAME VARCHAR(10), DESCRIPTION VARCHAR(20))
WITH REPLACE ON COMMIT PRESERVE ROWS NOT LOGGED
@
BEGIN
DECLARE V_ID1 INT DEFAULT 1;
DECLARE V_NAME1 VARCHAR(10) DEFAULT 'NAME1';
DECLARE V_DESC1 VARCHAR(20) DEFAULT 'DESC1';
DECLARE V_ID2 INT DEFAULT 2;
DECLARE V_NAME2 VARCHAR(10) DEFAULT 'NAME2';
DECLARE V_DESC2 VARCHAR(20) DEFAULT 'DESC2';
PREPARE S1 FROM '
MERGE INTO SESSION.MYTAB T USING
(
VALUES
(CAST(? AS INT), CAST(? AS VARCHAR(10)), CAST(? AS VARCHAR(20)))
, (CAST(? AS INT), CAST(? AS VARCHAR(10)), CAST(? AS VARCHAR(20)))
) S (ID, NAME, DESCRIPTION) ON T.ID = S.ID
WHEN MATCHED THEN UPDATE SET NAME = S.NAME, DESCRIPTION = S.DESCRIPTION
WHEN NOT MATCHED THEN INSERT (ID, NAME, DESCRIPTION) VALUES (S.ID, S.NAME, S.DESCRIPTION)
';
EXECUTE S1 USING
V_ID1, V_NAME1, V_DESC1
, V_ID2, V_NAME2, V_DESC2;
END
@
SELECT * FROM SESSION.MYTAB
@