2011-11-02 78 views
1

我用下面的查詢中插入新行:插入和在一個查詢默認值選擇

insert into table1 (c1, c2, c3) (select c1, c2, c3 from table2 where some_condition) 

這工作細如果在表2的行滿足some_condition。但是,如果沒有行,則不會插入任何內容。

如果select返回空結果集,是否有任何方法指定要插入的默認值?我想在一個SQL查詢中做到這一點。

回答

1

這是不是很漂亮,但你想要做什麼,你需要與你的環境中測試,看它是否執行不夠好

SQL> drop table so_tgt; 

Table dropped. 

SQL> 
SQL> create table so_src (
    2 c1 varchar2(6) 
    3 ,c2 varchar2(6) 
    4 ,c3 varchar2(6) 
    5 ); 

Table created. 

SQL> 
SQL> insert into so_src values ('foo','bar','moo'); 

1 row created. 

SQL> 
SQL> create table so_tgt as select * from so_src where 1 = 0; 

Table created. 

SQL> 
SQL> /* Test for existing row insert */ 
SQL> insert into so_tgt 
    2 with x as (select s.*, 1 as r 
    3   from so_src s 
    4   where c1='foo' 
    5   union 
    6   select 'x','y','z',0 as r /* DEFAULT VALUES */ 
    7   from dual) 
    8 select c1,c2,c3 
    9 from x 
10 where r = (select max(r) from x) ; 

1 row created. 

SQL> 
SQL> select * from so_tgt; 

C1  C2  C3 
------ ------ ------ 
foo bar moo 

SQL> truncate table so_tgt; 

Table truncated. 

SQL> 
SQL> /* Test for default row insert */ 
SQL> insert into so_tgt 
    2 with x as (select s.*, 1 as r 
    3   from so_src s 
    4   where c1='far' 
    5   union 
    6   select 'x','y','z',0 as r /* DEFAULT VALUES */ 
    7   from dual) 
    8 select c1,c2,c3 
    9 from x 
10 where r = (select max(r) from x) ; 

1 row created. 

SQL> 
SQL> select * from so_tgt; 

C1  C2  C3 
------ ------ ------ 
x  y  z 

SQL> truncate table so_tgt ; 

Table truncated. 
1

的快速和骯髒的方式,如果你不介意重複some_condition並在some_condition不依賴於在表2中的數值:

insert into table1 (c1,c2,c3) 
select c1, c2, c3 from table2 where some_condition 
union select defaultvalue1, defaultvalue2, defaultvalue3 from dual where not (some_condition) 

如果some_condition取決於值表2中,那麼你可以做(​​未經測試):

insert into table1 (c1,c2,c3) 
    select nvl(t2.c1, defaultvalue1), nvl(t2.c2, defaultvalue2), nvl(t2.c2, defaultvalue3) 
    from dual left join (select c1,c2,c3 from table2 where some_condition) t2 
    on 1 = 1 

如果我是正確的,這個查詢將始終返回至少一行,但如果沒有行右側出現了,那麼T2值都將返回空,所以nvl可以用於提供您的默認值。

編輯:小警告。這假設從table2返回的值不會爲空,或者如果它們是,則需要默認值。