2014-10-02 38 views
0

我想在下面的方式插入这些值:甲骨文)插入与一个固定值的多个行

insert into table (name, action-id) values ('user', select action from actions where name='user2'); 

其结果是:

插入沿的线,('user', 1) ('user', 2) ('user', 3)

我注意到这是不正确的SQL。 我将如何去完成这个?

注)

select action from actions where name='user2' 

将返回:(1,2,3)

回答

3

你可以用一个循环做到这一点:

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; 

,或者您可以使用INSERT/SELECT语法:

INSERT INTO table (name, action-id) 
    SELECT 'user', action 
    FROM actions WHERE name='user2'; 
+0

感谢,伟大工程! 你是如何做出与循环比较的。 – dk123 2014-10-02 16:20:52

2

添加固定值作为查询一栏,并用刀片式选择,而不是插入值:

insert into table (name, action-id) 
select 'user', action from actions where name='user2'; 
0
Or can be done by procedure 
Create that procedure and run it 
create or replace procedure set_action  


光标C1是
SELECT * FROM用户;
person c1%rowtype;
username varchar(8);
begin
username:='user';
的人C1循环
插入到表(名称,动作id)
值(用户名,person.action);
end loop;
end;
它可以通过执行set_action来运行;

+0

对于在普通SQL中轻松完成的事情,这是相当多的开销和复杂性... – 2014-10-02 16:06:23

0

例子:

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 

最后:
select * from testing; steve test2_col2 brad test2_col2 chad test2_col2 nick test2_col2