简体   繁体   中英

How to insert multiple insert sql statement

There is a table Person(id, name). I am inserting more than 1000 records into person table. Both id and name should be unique. I wrote something like this

INSERT ALL 
       INTO PERSON (1, 'MAYUR')
       INTO PERSON (2, 'SALUNKE') 
       .....(1000 records)
SELECT * FROM DUAL;    

I am getting unique constraint for name in this query. How do I know which record in particular is failing. All I see in logs is this

Error starting at line : 3 in command - ORA-00001: unique constraint (UN_PERSON_NAME) violated.

This does not tell the exact record which is duplicate.

You are missing values keyword. Try this!

INSERT ALL 
       INTO PERSON values(1, 'MAYUR')
       INTO PERSON values(2, 'SALUNKE') 
       .....(1000 records)
SELECT * FROM DUAL;    
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1

Unfortunately, Oracle doesn't support multiple inserts using a single VALUES() statement. I usually approach this as:

INSERT PERSON (id, name)
    SELECT 1, 'MAYUR' FROM DUAL UNION ALL
    SELECT 2, 'SALUNKE' FROM DUAL UNION ALL 
       .....;

One advantage of this approach is you can use a subquery and assign the id:

INSERT PERSON (id, name)
    SELECT rownum, x.name
    FROM (SELECT 'MAYUR' FROM DUAL UNION ALL
          SELECT 'SALUNKE' FROM DUAL UNION ALL 
          .....
         ) x

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