2013-10-04 35 views
1

我有一個字符串,其中包含由'/'字符分隔的項目層次結構。將返回的字符串拆分爲多個列

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不存在

例如

Mammalia\Carnivora\Felidae 

成爲

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

回答

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