Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert multiple rows into DB2 database

Tags:

sql

db2

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.

like image 853
Frantumn Avatar asked Jul 31 '12 15:07

Frantumn


People also ask

Which statement is used to multiple new rows in a table?

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.

Can we insert multiple rows single insert statement?

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?

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.


2 Answers

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.

like image 124
bhamby Avatar answered Oct 02 '22 05:10

bhamby


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') 
like image 24
Hogan Avatar answered Oct 02 '22 06:10

Hogan