2015-04-03 129 views
1

到目前为止,我已经编写了一个查询,将第一行拆分为多行,但以下N行的结果将返回N行,返回空值。用于根据字符将单行数据拆分为多行的SQL

这是场景。

select address from sample; 
这将返回以下4行,

Stack Overflow# is a# question and# answer site 
Stack Overflow# is a# question and# answer site 
Stack Overflow# is a# question and# answer site 
Stack Overflow# is a# question and# answer site 

当试图每一行拆分为使用下面的查询多行,

with test as (select address as str from sample) 
select regexp_substr (str, '[^#]+', 1, rownum) split 
from test 
connect by level <= length (regexp_substr (str, '[^#]+', 1, rownum)) + 1 
; 

以下值将返回

Stack Overflow 
is a 
question and 
answer site 
(null) 
(null) 
(null) 

为什么不能得到所有行的结果?

+1

请为您正在使用的RDBMS添加标签。这不是标准的SQL,它需要特定于实现的答案。 – Barmar 2015-04-03 04:30:13

+0

哦!我的错。它的Oracle – 2015-04-03 05:07:30

+0

我很高兴看到字符串拆分问题:-)我一直在回答这个问题的大多数相关的问题。你几乎接近你想要的输出,但是你做了两件事情根本错误。查看我的答案了解更多详情。 – 2015-04-03 11:26:28

回答

0

为什么不能得到所有行的结果?

您的查询有两件事情不正确。

  1. 因为使用ROWNUM的不正确。您在同一查询中使用ROWNUM作为条件,但是,ROWNUM尚未将递增到下一个值。所以,它的价值仅仅是一个。所以,你只得到1行。

  2. 您需要对所有行进行拆分,而不仅仅是第一行。你需要遍历所有的行。但是,在同一时间,你应该避免循环和摆脱重复。

有很多方法可以对多行​​进行字符串拆分。我在我的文章在这里http://lalitkumarb.wordpress.com/2015/03/04/split-comma-delimited-strings-in-a-table-using-oracle-sql/

例如演示,你可以做这样的:

SQL> WITH t AS(
    2 SELECT 'Stack Overflow# is a# question and# answer site' text FROM dual UNION ALL 
    3 SELECT 'Stack Overflow# IS a# question and# answer site' text FROM dual UNION ALL 
    4 SELECT 'Stack Overflow# is a# question and# answer site' text FROM dual UNION ALL 
    5 SELECT 'Stack Overflow# IS a# question and# answer site' text FROM dual 
    6 ) 
    7 SELECT trim(regexp_substr(t.text, '[^#]+', 1, lines.column_value)) text 
    8  FROM t, 
    9  TABLE (CAST (MULTISET 
10  (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(t.text, '#')+1) 
11      AS sys.odciNumberList 
12     ) 
13    ) lines 
14/

TEXT 
----------------------------------------------- 
Stack Overflow 
is a 
question and 
answer site 
Stack Overflow 
IS a 
question and 
answer site 
Stack Overflow 
is a 
question and 
answer site 
Stack Overflow 
IS a 
question and 
answer site 

16 rows selected. 

SQL> 

所以,你现在得到16行。完美的作品!