简体   繁体   中英

Can't insert multiple values into DB2 by using UNION ALL and generate IDs from sequence

I've created sequence by following statement:

CREATE SEQUENCE MAIN.MY_SEQUENCE START WITH 1 INCREMENT BY 1 CACHE 50;

And table by following statement:

CREATE TABLE MAIN.EMPLOYEES(
        ID INTEGER NOT NULL, 
        NAME VARCHAR(512), 
        EMAIL VARCHAR(254),

        PRIMARY KEY (ID)
) 

Now when I try to insert a new record by using following statement:

INSERT INTO MAIN EMPLOYEES (ID, NAME, EMAIL) 
VALUES (MAIN.MY_SEQUENCE.NEXTVAL, 'Name 1', 'email1@example.com') UNION ALL
VALUES (MAIN.MY_SEQUENCE.NEXTVAL, 'Name 2', 'email2@example.com')

I get an error:

"NEXTVAL FOR MAIN.MY_SEQUENCE.NEXTVAL" cannot be specified in this context.. SQLCODE=-348, SQLSTATE=428F9, DRIVER=4.17.30

When I try to insert a single row everything works fine.

I have found a list of restrictions on using NEXT VALUE here but here not mentioned my case or I couldn't find it.

My question is it possible to insert multiple rows by using ID from sequence, and if yes, how can I achieve it?

It does list your case. The documentation contains this:

The NEXT VALUE expressions cannot be specified in the following contexts:
...
•SELECT statement for which the outer SELECT is combined with another SELECT statement using a set operator such as UNION, EXCEPT, or INTERSECT
....

(emphasis mine) This statement isn't exhaustive, and because UNION ALL is considered a set operation, the operation is excluded.

This should be fixable - I'm a little surprised you wrote the statement the way you did; DB2 allows you to comma-separate data rows. That is, the following should be valid:

INSERT INTO MAIN.EMPLOYEES (ID, NAME, EMAIL) 
VALUES (MAIN.MY_SEQUENCE.NEXTVAL, 'Name 1', 'email1@example.com'),  
       (MAIN.MY_SEQUENCE.NEXTVAL, 'Name 2', 'email2@example.com')

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