基于条件的SQL换行符

时间:2013-10-21 08:04:53

标签: sql sql-server sql-server-2008

在SELECT之后我得到这样的价值:

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: - 中间有4个空格

1 个答案:

答案 0 :(得分:0)

这适用于您的示例,但您必须根据实际数据进行测试才能确定。

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

如果需要更正,请更新附加样本的问题。