Sql 使用另一列中的选定结果更新选定行
我有一个名为“example”的表,在一列“colname2”中有如下字符串数据Sql 使用另一列中的选定结果更新选定行,sql,oracle,Sql,Oracle,我有一个名为“example”的表,在一列“colname2”中有如下字符串数据 colname1 colname2 colname3 101 this is - test 50 this is - test2 105 this is - test31ws 我需要做以下事情 选择colname1>100的位置,然后 将colname2字符串拆分为“-”,并取“-”的最后一部分,然后 将最后一部分添加到colname3 所以输出应该是这样的
colname1 colname2 colname3
101 this is - test
50 this is - test2
105 this is - test31ws
我需要做以下事情
colname1 colname2 colname3
101 this is - test test
50 this is - test2
105 this is - test31ws test31ws
我正在使用oracle数据库。
SUBSTR
是最简单的,可能也是最有效的。下面是一个例子:
SQL> create table example
2 (colname1 number,
3 colname2 varchar2(20),
4 colname3 varchar2(20));
Table created.
SQL> insert into example
2 (select 101, 'this is - test' , null from dual union
3 select 50 , 'this is - test2' , null from dual union
4 select 105, 'this is - test31ws', null from dual
5 );
3 rows created.
SQL> update example set
2 colname3 = trim(substr(colname2, instr(colname2, '-') + 1))
3 where colname1 > 100;
2 rows updated.
SQL> select * from example;
COLNAME1 COLNAME2 COLNAME3
---------- -------------------- --------------------
50 this is - test2
101 this is - test test
105 this is - test31ws test31ws
SQL>
您可以使用
case
和regexp_substr()
如果没有连字符,这将返回
NULL
。似乎应该修剪一个空格。@Littlefoot。最后,我同意你的看法。这不是OP特别要求的,而是数据的样子和原因。
select t.*,
(case when colname1 > 100 then trim(regexp_substr(colname2, '[^-]+', 1, 2))
end) as colname3
from t;