2014-10-02 39 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