问题
I'd like to insert these values in the following fashion:
insert into table (name, action-id) values ('user', select action from actions where name='user2');
The result being:
Inserts along the line of, ('user', 1) ('user', 2) ('user', 3)
I'm noticing this isn't correct sql. How would I go about accomplishing this?
note)
select action from actions where name='user2'
would return: (1, 2, 3)
回答1:
You can do it with a loop:
BEGIN
FOR x IN (select action from actions where name='user2') LOOP
insert into table (name, action-id) values ('user', x.action)
END LOOP;
END;
or you could use the INSERT/SELECT syntax:
INSERT INTO table (name, action-id)
SELECT 'user', action
FROM actions WHERE name='user2';
回答2:
Add the fixed value as a column in your query, and use insert-select instead of insert-values:
insert into table (name, action-id)
select 'user', action from actions where name='user2';
回答3:
Or can be done by procedure
Create that procedure and run it
create or replace procedure set_action
as
cursor c1 is
select * from user;
person c1%rowtype;
username varchar(8);
begin
username:='user';
for person in c1 loop
insert into table(name,action-id)
values (username,person.action);
end loop;
end;
It can be run by execute set_action;
回答4:
Example:
create table testing(col1 varchar2(10), col2 varchar2(10));
create table testing2(col1 varchar2(10), col2 varchar2(10));
create table testing3(col1 varchar2(10), col2 int);
insert into testing2 (col1, col2) values ('test2_col1', 'test2_col2');
insert into testing3(col1, col2) values ('steve', 1);
insert into testing3(col1, col2) values ('brad', 2);
insert into testing3(col1, col2) values ('chad', 3);
insert into testing3(col1, col2) values ('nick', 1);
insert into testing(col1, col2)
(select col1 ,(select col2 from testing2) from testing3); -- inserts 4 rows
And finally:
select * from testing;
steve test2_col2
brad test2_col2
chad test2_col2
nick test2_col2
来源:https://stackoverflow.com/questions/26164455/oracle-insert-multiple-rows-with-one-fixed-value