2015-04-03 161 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行。完美的作品!

相關問題