oracle10g中多行的单列更新

时间:2011-09-21 07:37:50

标签: oracle oracle10g

Update table_1 set col1= 1 where col2 = 'ONE';  
update table_1 set col1= 2 where col2 = 'TWO';  
Update table_1 set col1= 3 where col2 = 'THREE';
...
update table_1 set col1= 100 where col2 = 'HUNDRED';

有没有简单的方法在单个查询中实现这一点而不是在oracle10g中编写100个更新状态网?

2 个答案:

答案 0 :(得分:2)

我认为可能有Oracle Case-Statement或decode-function的解决方案,虽然这将是一个很长的声明,我不太确定100个更新语句的优势是什么。另外,我不知道参数列表的长度等有任何限制。

案例:

update table_1
set col1 = CASE col2
  WHEN 'ONE' THEN 1
  WHEN 'TWO' THEN 2
  WHEN 'THREE' THEN 3
  WHEN 'FOUR' THEN 4
  WHEN 'FIVE' THEN 5
  WHEN 'SIX' THEN 6
  WHEN 'SEVEN' THEN 7
  WHEN 'EIGHT' THEN 8
  ...
  WHEN 'HUNDRED' THEN 100
  ELSE col2
END;

解码示例:

update table_1
set col1 = decode(col2,
              'ONE', 1,
              'TWO', 2,
              'THREE', 3,
              'FOUR', 4,
              'FIVE', 5,
              'SIX', 6,
              'SEVEN', 7,
              'EIGHT', 8,
              ...
              'HUNDRED', 100,
              col2);

答案 1 :(得分:0)

您可以使用Julian拼写格式(有关详细信息,请搜索asktom.oracle.com)

以下是我的会话的输出: -

create table table_1 (col_1 number, col_2 varchar(20))

insert into table_1 (col_1, col_2) values (null, 'THIRTY-THREE')
insert into table_1 (col_1, col_2) values (null, 'SEVEN')
insert into table_1 (col_1, col_2) values (null, 'EIGHTY-FOUR')

select * from table_1 
COL_1     COL_2     
       THIRTY-THREE     
       SEVEN    
       EIGHTY-FOUR

update /*+bypass_ujvc*/
(select t1.col_1, spelled.n
from
table_1 t1
inner join
(select n, to_char(to_date (n, 'J'),'JSP') spelled_n from
(select level n from dual connect by level <= 100)) spelled
on t1.col_2 = spelled.spelled_n
)
set col_1 = n

select * from table_1

COL_1 COL_2
33     THIRTY-THREE
7      SEVEN
84     EIGHTY-FOUR

讨厌的提示(bypass_ujvc)忽略了内联视图不是密钥保留的事实 - 实际上你应该使用合并语句。但这不是一个现实世界的场景,对吧! (而且你必须将'HUNDRED'作为特殊情况对待='一百个'。)