多次插入相同的数据

时间:2014-10-21 00:29:52

标签: sql oracle plsql

我有一个与此类似的插入语句:

insert into table (id, name, descr) values (4, 'asdf', 'this is not a word');

我需要使用多个id插入此相同的语句。现在我有:

insert into table (id, name, descr) values (4, 'asdf', 'this is not a word');
insert into table (id, name, descr) values (6, 'asdf', 'this is not a word');
insert into table (id, name, descr) values (7, 'asdf', 'this is not a word');
insert into table (id, name, descr) values (9, 'asdf', 'this is not a word');

我是否只需要运行它,或者是否有更精简的版本?

4 个答案:

答案 0 :(得分:7)

使用select . . . insert

insert into table(id, name, descr) 
    select i.id, 'asdf', 'this is not a word'
    from (select 4 as id from dual union all
          select 6 from dual union all
          select 7 from dual union all
          select 9 from dual
         ) i;

答案 1 :(得分:2)

您可以使用INSERT ALL声明

INSERT ALL
  INTO table (id, name, descr) VALUES (4, 'asdf', 'this is not a word')
  INTO table (id, name, descr) VALUES (6, 'asdf', 'this is not a word')
  INTO table (id, name, descr) VALUES (7, 'asdf', 'this is not a word')
  INTO table (id, name, descr) VALUES (9, 'asdf', 'this is not a word')
SELECT * FROM dual;

答案 2 :(得分:2)

INSERT INTO [TableName] (id, name, descr) VALUES 
(4, 'asdf', 'this is not a word'),
(6, 'asdf', 'this is not a word'),
(7, 'asdf', 'this is not a word'),
(9, 'asdf', 'this is not a word')

答案 3 :(得分:0)

为了参数起见,如果该ID也是primary_key,可以通过创建序列,向表中添加BEFORE INSERT触发器以自动使用序列递增ID,然后循环插入来创建更永久的解决方案你想要的很多行,让ID自行增加:

-- Create the table    
CREATE TABLE SEQ_TEST
(
  ST_ID    NUMBER,
  ST_NAME  VARCHAR2(50 BYTE),
  ST_DESC  CHAR(100 BYTE)
);

-- Create the sequence
CREATE SEQUENCE SEQ_TEST_SEQ
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 0
  NOCYCLE
  NOCACHE
  ORDER;

-- Create the before insert trigger
CREATE OR REPLACE TRIGGER SEQ_TEST_BI
BEFORE INSERT
ON SEQ_TEST
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN

  if :old.ST_ID is null then
    :new.ST_ID := SEQ_TEST_SEQ.nextval;
  end if;

END SEQ_TEST_BI;

-- insert 25 rows using an anonymous block.  Note the ID is NULL 
--  which causes the trigger to increment ID
--  based on the sequence.
begin
  for i in 1..25
  loop
    -- NOTE - Technically you could omit the 'ST_ID' and NULL and it would
    --        still work, but I prefer to keep them here to show this action 
    --        of inserting NULL is intentional and show that all columns are
    --        accounted for in the insert.  
    insert into SEQ_TEST (ST_ID, ST_NAME, ST_DESC) values (NULL, 'asdf', 'this is not a word');
  end loop;
end;

commit;

-- Prove it.
select * from seq_test;