在Oracle中使用子串和Instirng

时间:2014-01-27 14:59:26

标签: sql oracle oracle11g oracle-sqldeveloper

我有一个问题:

       Select SUBSTR(concat_prod_id,1,(INSTR(concat_prod_id,',',1,1)-1)) AS Test
       from        dims_doc_master
       where pyid='D-122663'

现在Concat_pord_id的值类似于'121,122,123',此字符串中的值数可以从1到任意数字不等。上面的查询只返回121,就是这样。我想要的是这个查询返回3个不同的行结果:

1. 121
2. 122
3. 123.

请建议

2 个答案:

答案 0 :(得分:3)

使用此查询,这适用于任意数量的行:

WITH tab(str) AS (SELECT '121,122,123' FROM dual UNION ALL
                  SELECT '221,222,223' FROM dual UNION ALL
                  SELECT '321,322,323' FROM dual)
------------
---End of data
------------
SELECT REGEXP_SUBSTR (str,'[^,]+',1,LEVEL) txt
  FROM tab
CONNECT BY REGEXP_SUBSTR (str,'[^,]+',1,LEVEL) IS NOT NULL
   AND PRIOR str = str
   AND PRIOR sys_guid() IS NOT NULL;

输出:

| TXT |
|-----|
| 121 |
| 122 |
| 123 |
| 221 |
| 222 |
| 223 |
| 321 |
| 322 |
| 323 |

您的查询:

SELECT REGEXP_SUBSTR(concat_prod_id,'[^,]+',1,LEVEL) AS test
  FROM dims_doc_master
 WHERE pyid = 'D-122663'
CONNECT BY REGEXP_SUBSTR(concat_prod_id,'[^,]+',1,LEVEL) IS NOT NULL
   AND PRIOR concat_prod_id = concat_prod_id
   AND PRIOR sys_guid() IS NOT NULL; 

答案 1 :(得分:0)

试试这个

SELECT REGEXP_SUBSTR ('121,122,123','[^,]+',1,LEVEL) txt
FROM DUAL
CONNECT BY LEVEL <=
LENGTH ('121,122,123') - LENGTH (REPLACE ('121,122,123',',')) + 1