[英]How to write conditional select insert statement to fetch record from a table, and based on some particular column's values
例如:
表格1:
c1,c2,c3 (1,10,'123')
表2
c1,c2,c3,c4
現在我想從 table1 中選擇記錄,如果 c3 列值開始兩位數是 12 那么我必須填充 AA,如果 34 那么 BB 在 Table2 c4 列中:
OP 在原始帖子下的評論中提供了更多信息。 特別是, c3
是VARCHAR2
並且總是以12
或34
開頭。
以下應該工作。 如果c3
不以12
或34
開頭,則插入列c4
的值將為NULL
。 這是CASE
表達式的默認行為,因此不需要顯式編碼; 如果在這種情況下需要像'ZZ'
這樣'ZZ'
東西,那么我們可以向CASE
添加一個else
子句。 (OP 說c3
總是以12
或34
開頭;如果是這樣,這是一個有爭議的問題。)
insert into table2 ( c1, c2, c3, c4 )
select c1, c2, c3,
case when c3 like '12%' then 'AA'
when c3 like '34%' then 'BB'
end
from table1
;
演示:
SQL> create table table1 ( c1 number, c2 number, c3 varchar2(25) );
Table created.
SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '123' );
1 row created.
SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '3444' );
1 row created.
SQL> commit;
Commit complete.
SQL> select * from table1;
C1 C2 C3
---------- ---------- -------------------------
1 10 123
1 10 3444
2 rows selected.
然后:
SQL> create table table2 ( c1 number, c2 number, c3 varchar2(25), c4 varchar2(10) );
Table created.
SQL> select * from table2;
no rows selected
SQL> insert into table2 ( c1, c2, c3, c4 )
2 select c1, c2, c3,
3 case when c3 like '12%' then 'AA'
4 when c3 like '34%' then 'BB'
5 end
6 from table1
7 ;
2 rows created.
SQL> select * from table2;
C1 C2 C3 C4
---------- ---------- ------------------------- ----------
1 10 123 AA
1 10 3444 BB
2 rows selected.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.