将具有常规字词的字符串拆分为列

时间:2016-08-06 02:50:32

标签: sql string return sql-server-2014

我在使用以下查询时遇到问题。我需要根据LineFeeds将字符串值拆分为新列。

数据显示为

|NUMBER   |Answer
|RN110455 |very satisfied very satisfied very satisfied very satisfied very satisfied |

我遇到了以下代码部分但是我一直收到以下错误消息

  

消息240,级别16,状态1,行1类型之间不匹配   列和#34; SplitValue"列中的锚点和递归部分递归的   查询" SplitValues"。

我希望有人可以告诉我哪里出错了,因为我无法弄明白。我相信所有类型都匹配。

;WITH SplitValues (ID, OriginalValue, SplitValue, Level)
AS
(
    SELECT  i.Number, i.ANSWER, CAST('' AS VARCHAR(MAX)), 0 FROM Survey i

    UNION ALL

    SELECT  ID
    ,   SUBSTRING(OriginalValue, CASE WHEN CHARINDEX(CHAR(13), OriginalValue) = 0 THEN LEN(OriginalValue) + 1 ELSE CHARINDEX(CHAR(13), OriginalValue) + 2 END, LEN(OriginalValue))
    ,   SUBSTRING(OriginalValue, 0, CASE WHEN CHARINDEX(CHAR(13), OriginalValue) = 0 THEN LEN(OriginalValue) + 1 ELSE CHARINDEX(CHAR(13), OriginalValue) END)
    ,   Level + 1
    FROM    SplitValues
    WHERE   LEN(SplitValues.OriginalValue) > 0
)

SELECT  ID, [1] AS Level1, [2] AS Level2, [3] AS Level3, [4] AS Level4, [5] AS Level5
FROM    (
    SELECT  ID, Level, SplitValue
    FROM    SplitValues
    WHERE   Level > 0
    ) AS p
PIVOT   (MAX(SplitValue) FOR Level IN ([1], [2], [3], [4], [5])) AS pvt

上面的代码似乎是最适合目的的解决方案,但我还没到达那里。

我正在跑步。 Microsoft SQL Server 2014

2 个答案:

答案 0 :(得分:1)

试试这个。你也必须施放i.Answer。

;WITH SplitValues (ID, OriginalValue, SplitValue, Level)
AS
(
    SELECT  'RN110455', cast('very satisfied very satisfied very satisfied very satisfied very satisfied' as varchar(max))
    , CAST('' AS VARCHAR(MAX)), 0 

    UNION ALL

    SELECT  ID
    ,   SUBSTRING(OriginalValue, CASE WHEN CHARINDEX(CHAR(13), OriginalValue) = 0 THEN LEN(OriginalValue) + 1 ELSE CHARINDEX(CHAR(13), OriginalValue) + 2 END, LEN(OriginalValue))
    ,   SUBSTRING(OriginalValue, 0, CASE WHEN CHARINDEX(CHAR(13), OriginalValue) = 0 THEN LEN(OriginalValue) + 1 ELSE CHARINDEX(CHAR(13), OriginalValue) END)
    ,   Level + 1
    FROM    SplitValues
    WHERE   LEN(SplitValues.OriginalValue) > 0
)

SELECT  ID, [1] AS Level1, [2] AS Level2, [3] AS Level3, [4] AS Level4, [5] AS Level5
FROM    (
    SELECT  ID, Level, SplitValue
    FROM    SplitValues
    WHERE   Level > 0
    ) AS p
PIVOT   (MAX(SplitValue) FOR Level IN ([1], [2], [3], [4], [5])) AS pvt

答案 1 :(得分:0)

在上述CTE中的字符串变量上声明VARCHAR(max)数据类型,而不是NVARCHAR(MAX)。