I want to insert multiple rows into a DB2 table. I have a query that looks like this
insert into tableName (col1, col2, col3, col4, col5) values (val1, val2, val3, val4, val5), (val1, val2, val3, val4, val5), (val1, val2, val3, val4, val5), (val1, val2, val3, val4, val5);
This query does't work. I don't know if there is a more syntactically correct way to do this in DB2. But it'd be useful to insert my test data.
If you want to add data to your SQL table, then you can use the INSERT statement. In this article, I will show you how to use the INSERT statement to add a single row, multiple rows, and to copy rows from one SQL table to another.
Answer. Yes, instead of inserting each row in a separate INSERT statement, you can actually insert multiple rows in a single statement. To do this, you can list the values for each row separated by commas, following the VALUES clause of the statement.
Is it possible to insert more than one row at a time using an INSERT statement with a VALUES clause? Yes, you can just list as many rows as you want; just remember to separate the rows with commas.
I'm assuming you're using DB2 for z/OS, which unfortunately (for whatever reason, I never really understood why) doesn't support using a values-list where a full-select would be appropriate.
You can use a select like below. It's a little unwieldy, but it works:
INSERT INTO tableName (col1, col2, col3, col4, col5) SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1
Your statement would work on DB2 for Linux/Unix/Windows (LUW), at least when I tested it on my LUW 9.7.
UPDATE - Even less wordy version
INSERT INTO tableName (col1, col2, col3, col4, col5) VALUES ('val1', 'val2', 'val3', 'val4', 'val5'), ('val1', 'val2', 'val3', 'val4', 'val5'), ('val1', 'val2', 'val3', 'val4', 'val5'), ('val1', 'val2', 'val3', 'val4', 'val5')
The following also works for DB2 and is slightly less wordy
INSERT INTO tableName (col1, col2, col3, col4, col5) VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL VALUES ('val1', 'val2', 'val3', 'val4', 'val5')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With