Extract nth substring [duplicate]

戏子无情 提交于 2020-01-06 04:26:31

问题


I need to extract a sub string from a string. Given below are the IDs that are available.

0234-RDRT-RS111-M-EU

0234-RDRT-RSD123-M-EU

I need to extract the highlighted ones to a column. How do I extract all the characters to the same column in Microsoft SQL Server.


回答1:


The fourth parameter of REGEX_SUBSTR is the called occurence. You just have to set the occurence you want to see for each column:

CREATE TABLE T (id varchar2(30));
INSERT INTO T VALUES ('0234-RDRT-RS111-M-EU');
INSERT INTO T VALUES ('0234-RDRT-RSD123-M-EU');

SELECT regexp_substr(id,'[^-]+',1,1) as col1,
       regexp_substr(id,'[^-]+',1,2) as col2,
       regexp_substr(id,'[^-]+',1,3) as col3,
       regexp_substr(id,'[^-]+',1,4) as col4,
       regexp_substr(id,'[^-]+',1,5) as col5
  FROM t;

COL1    COL2    COL3    COL4    COL5
0234    RDRT    RS111   M   EU
0234    RDRT    RSD123  M   EU

See REGEX_SUBSTR in Oracle's documentation for more details.




回答2:


You can extract all the values of your column id by spliting them on the dash

select regexp_substr(id,'[^-]+', 1, level) 
from (select '0234-RDRT-RSD123-M-EU' as id 
        from dual)
connect by regexp_substr(id, '[^-]+', 1, level) is not null

the result has 5 lines. You can then exploit the result as needed




回答3:


Split based on '-' , store in string array then take 3rd element .



来源:https://stackoverflow.com/questions/51045592/extract-nth-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!