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

拜拜、爱过 提交于 2019-12-12 02:22:36

问题


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?


回答1:


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')


来源:https://stackoverflow.com/questions/34381352/cant-insert-multiple-values-into-db2-by-using-union-all-and-generate-ids-from-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!