1

「/」文字で区切られたアイテムの階層を含む文字列があります。

例: Class\Order\Family\Genus\Species

各値が独自の列になり、元の完全な文字列が表示されるように、この文字列を分割する必要があります

例えば

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 に答える