到目前为止,我编写了一个查询,将第一行拆分为多行,但后面N行的结果将是N行返回空值。
以下是该方案。
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)
为什么我无法获得所有行的结果?
答案 0 :(得分:0)
为什么我无法获得所有行的结果?
您的查询有两件事不正确。
因为 ROWNUM 的使用不正确。您在同一查询中使用ROWNUM作为条件,但是,ROWNUM尚未递增到下一个值。所以,它的价值只有一个。所以,你只得到一行。
您需要对所有行进行拆分,而不仅仅是第一行。您需要循环遍历所有行。但是,与此同时,你应该避免循环循环并摆脱重复。
有多种方法可以为多行执行字符串拆分。我在我的文章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行。效果很好!