将返回字符串拆分为多个列

时间:2013-10-04 01:10:39

标签: sql sql-server

我有一个字符串,其中包含由'/'字符分隔的项目层次结构。

E.g。类\订单\家庭\属\种

我需要拆分这个字符串,使每个值都是自己的列,并显示原始的完整字符串

E.g。

Mammalia\Carnivora\Felidae\Panthera\Panthera tigris  
Mammalia\Carnivora\Felidae\Panthera\Panthera leo  
Mammalia\Carnivora\Felidae\Panthera\Panthera pardus  

变为

Classification Class Order Family  Genus Species  
-------------- ----- ----- ------  ----- -------
Mammalia\Carnivora\Felidae\Panthera\tigris Mammalia  Carnivora Felidae Pathera tigris  
Mammalia\Carnivora\Felidae\Panthera\leo Mammalia  Carnivora Felidae Pathera leo  
Mammalia\Carnivora\Felidae\Panthera\pardus  Mammalia  Carnivora Felidae Pathera pardus  

最后,并非所有字符串都有5个值,因此脚本需要 为不存在的值输入NULL

E.g。

Mammalia\Carnivora\Felidae  

变为

Classification Class Order Family  Genus Species  
Mammalia\Carnivora\Felidae Mammalia  Carnivora Felidae NULL NULL

1 个答案:

答案 0 :(得分:0)

这应该做你想要的。

它使用公用表表达式将字符串拆分为多个部分(级别)。请注意,我不需要添加\来正确拆分它,因此输入字符串最后不应该有\

然后你只需获得每个级别的值。

DECLARE @string NVARCHAR(500) = 'Mammalia\Carnivora\Felidae\Panthera\Panthera tigris'

;WITH cte
AS
(
    SELECT SUBSTRING(@string + '\', 1, CHARINDEX('\', @string, 1) - 1) AS Part, 
        SUBSTRING(@string + '\', CHARINDEX('\', @string, 1) + 1, LEN(@string + '\') - CHARINDEX('\', @string, 1) + 1) AS Remainder,
        0 AS Level

    UNION ALL

    SELECT SUBSTRING(cte.Remainder, 1, CHARINDEX('\', cte.Remainder, 1) - 1) AS Part, 
        SUBSTRING(cte.Remainder, CHARINDEX('\', cte.Remainder, 1) + 1, LEN(cte.Remainder) - CHARINDEX('\', cte.Remainder, 1) + 1) AS Remainder,
        cte.Level + 1 AS Level
    FROM cte
    WHERE CHARINDEX('\', cte.Remainder, 1) > 0
)

SELECT
    @string Classification,
    (SELECT Part FROM cte WHERE Level = 0) Class,
    (SELECT Part FROM cte WHERE Level = 1) [Order],
    (SELECT Part FROM cte WHERE Level = 2) Family,
    (SELECT Part FROM cte WHERE Level = 3) Genus,
    (SELECT Part FROM cte WHERE Level = 4) Species