簡體   English   中英

如何編寫條件選擇插入語句以從表中獲取記錄,並基於某些特定列的值

[英]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 列中:

  • 表 1 -- (1,10,'123')
  • 表2 -- (1,10,'123','AA')

  • 表 1 -- (1,10,'3444')
  • 表 2 -- (1,10,'3444','BB')

OP 在原始帖子下的評論中提供了更多信息。 特別是, c3VARCHAR2並且總是以1234開頭。

以下應該工作。 如果c3不以1234開頭,則插入列c4的值將為NULL 這是CASE表達式的默認行為,因此不需要顯式編碼; 如果在這種情況下需要像'ZZ'這樣'ZZ'東西,那么我們可以向CASE添加一個else子句。 (OP 說c3總是以1234開頭;如果是這樣,這是一個有爭議的問題。)

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM