2013-10-21 67 views
0

一個SELECT我收到值這樣的後:SQL換行符根據病情

Basic:   3 Years/36,000 Miles Drivetrain:   3 Years/36,000 Miles Corrosion:   6 Years/100,000 Miles Roadside Assistance:   3 Years/36,000 Miles 

我希望它在兩列拆分,如:

Text   Value 

    Basic  3 Years/36,000 Miles 
    Drivetrain 3 Years/36,000 Miles 

etc 

注:

Basic:-----------3 Years/36,000 Miles- 之間有11個空格

3 Years/36,000 Miles----Drivetrain: - 有在

+0

你的表的模式是什麼,你可以提供select語句嗎? –

+0

'SELECT Text FROM Info' - Text的數據類型是'ntext' - 這裏給出了一個我用空格說的長行.. – James

+0

使用http://sqlfiddle.com發佈你的表和數據 – Tarik

回答

0

之間的正常工作與你的樣品4個空格,但你必須要測試它針對真實的數據是肯定的。

WITH CTE_StringSplit AS 
(
    SELECT CAST(NULL AS NVARCHAR(MAX)) AS [Text], CAST(NULL AS NVARCHAR(MAX)) AS [Value] , CAST([Text] AS NVARCHAR(MAX)) AS RemainingText 
    FROM Info 
    UNION ALL 
    SELECT 
     SUBSTRING(RemainingText,0,CHARINDEX('   ',RemainingText)) 
     ,LTRIM(SUBSTRING(RemainingText,CHARINDEX('   ',RemainingText),CASE WHEN CHARINDEX(' ',LTRIM(SUBSTRING(RemainingText,CHARINDEX('   ',RemainingText),DATALENGTH(RemainingText)))) > 0 THEN CHARINDEX(' ',LTRIM(SUBSTRING(RemainingText,CHARINDEX('   ',RemainingText),DATALENGTH(RemainingText)))) ELSE DATALENGTH(RemainingText) END + 11)) 
     ,LTRIM(SUBSTRING(RemainingText,11 + CHARINDEX('   ',RemainingText) + CASE WHEN CHARINDEX(' ',LTRIM(SUBSTRING(RemainingText,CHARINDEX('   ',RemainingText),DATALENGTH(RemainingText)))) > 0 THEN CHARINDEX(' ',LTRIM(SUBSTRING(RemainingText,CHARINDEX('   ',RemainingText),DATALENGTH(RemainingText)))) ELSE DATALENGTH(RemainingText) END,DATALENGTH(RemainingText))) 
    FROM CTE_StringSplit 
    WHERE LEN(RemainingText)>0 
) 
SELECT [Text],[Value] 
FROM CTE_StringSplit 
WHERE [Text] IS NOT NULL 

請更新與額外的樣品問題,如果需要更正。