2

我在交替这张表时遇到了一些麻烦:

我的桌子是styles( id, style)

id    Style      
------------
01   Style-01 
02   Style-02 
03   Style-03
04   Table
06   Chair

我需要将单词“Style-XX”更改为 Coach-XX,其中 XX 是偶数(0、2、4、6)。

所以它看起来像这样:

id    Style      
------------
01   Coach-02 
02   Style-03 
03   Coach-04
04   Table
06   Chair

好吧,我知道它必须是这样的:XX mod 2 = 0,才能使数字为偶数(0、2、4 等)。

但我真的不知道如何分开这些词:S

4

3 回答 3

0
MERGE INTO style s
USING (
   SELECT id
   FROM style ss
   WHERE ss.style LIKE 'Style%'
   AND  mod(to_number(substr(ss.style,6)),2)=0)e
   ON (s.id = e.id
      )
 WHEN MATCHED THEN
  UPDATE SET style =replace(style,'Style','Coach');

SQLFIDDLE:链接

于 2012-12-08T18:24:55.687 回答
0

如果您需要更改数据:

update STYLES set STYLE = 'Coach-'||substr(STYLE,-2,2)
where STYLE like 'Style-__'
  and substr(STYLE,-2,2) between '00' and '99'
  and mod(to_number(substr(STYLE,-2,2)),2) = 0;

如果只需要在读取数据时进行转换:

select 
  ID
 ,case
    when STYLE like 'Style-__'
     and substr(STYLE,-2,2) between '00' and '99'
     and mod(to_number(substr(STYLE,-2,2)),2) = 0
    then 'Coach-'||substr(STYLE,-2,2)
    else STYLE
  end as STYLE
from STYLES;
于 2012-12-08T18:40:17.877 回答
0

你的问题让我有点困惑,因为这些词与你的例子不太匹配。无论如何,如何使用一个简单的UPDATE步骤,如下所示:

update your_table
from (
   select id
        , case
             when Style = 'Style-01' then 'Coach-02'
             when Style = 'Style-03' then 'Coach-04'
             when Style = 'Style-05' then 'Coach-06'
             when Style = 'Style-07' then 'Coach-08'
             when Style = 'Style-09' then 'Coach-00'
             end as new_style
   from  your_table
   where Style in ('Style-01','Style-03','Style-05'
                   'Style-07','Style-09'
   ) x

set Style = x.new_style

where your_table.id = x.id

我认为明确地做事情比试图解析一个值并做算术更好。如果您需要重新访问代码,这样的事情会更容易理解。

于 2012-12-08T16:24:46.947 回答