如何在Oracle中拆分逗号分隔的字符串

时间:2017-05-30 10:49:47

标签: string oracle substr

如何使用SUBSTRINSTR在Oracle中拆分逗号分隔的字符串。

字符串' 20.4,12.5,3.5,0.2,0.2'

我尝试使用以下代码,但我在第二个逗号后无法获得该值。

SELECT substr('20.4,12.5,3.5,0.2,0.2',0,instr('20.4,12.5,3.5,0.2,0.2',',')-1) 
value FROM dual   -- 1. 20.4

第二个值我在第二个逗号后得到整个字符串。

SELECT substr('20.4,12.5,3.5,0.2,0.2',instr('20.4,12.5,3.5,0.2,0.2',',')+1,instr('20.4,
12.5,3.5,0.2,0.2',',',2,2)-1) st FROM dual   -- result : 12.5,3.5,

我想要每个逗号后面的值,比如

20.4

12.5

3.5等等。

3 个答案:

答案 0 :(得分:5)

基于https://blogs.oracle.com/aramamoo/how-to-split-comma-separated-string-and-pass-to-in-clause-of-select-statement

首先,我们将形成一个查询,它将这个以逗号分隔的字符串拆分,并将各个字符串作为行。

SQL> select regexp_substr('20.4,12.5,3.5,0.2,0.2','[^,]+', 1, level) from dual
     connect by regexp_substr('20.4,12.5,3.5,0.2,0.2', '[^,]+', 1, level) is not null;


REGEXP_SUBSTR('20.4,1
---------------------
20.4                 
12.5                 
3.5                  
0.2                  
0.2  

上面的查询遍历逗号分隔的字符串,搜索逗号(,)然后通过将逗号视为分隔符来拆分字符串。只要它到达分隔符,它就会将字符串作为一行返回。

答案 1 :(得分:1)

  
    

您还可以检查逗号之间是否有特定的出现,样本或第二次出现。

  
SQL> select regexp_substr('20.4,12.5,3.5,0.2,0.2','[^,]+[^,]', 1,2 ) as 2nd_occur 
     from dual;

 ", 1,2 )" -- You can replace this query part to choose with occurrence you want, like 

 ", 1,3 )" -- for third occurrence.`


Output:

2nd_occur
---------
12.5

答案 2 :(得分:0)

如果您的数据库中安装了APEX 5.1或更高版本,则可以使用apex_string.split很好地解决此问题:

jq -nr '
["timestamp","transmitterId","receiverId","rssi"],
 (inputs |
  [.timestamp, .transmitterId] + (.rssiSignature[] | [.receiverId,.rssi]))
| @csv'