1

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

例如类\顺序\家庭\属\物种

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

例如

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

例如

Mammalia\Carnivora\Felidae  

变成

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

1 回答 1

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
于 2013-10-04T03:42:20.933 回答