0

次のような構造のテーブルがあります

name    properties
x       thing1, thing2, thing3
y       otherthing1, otherthing2, otherthing3

これを1対多の関係にマッピングしたいと思います

name  properties
x     thing1
x     thing2
x     thing3

私が持っているこの次のソリューションは機能しますが、SQL Server の Maxrecursion オプションに対して実行されます

;with tmp(brandName, drugList, genericName) as (
select brandName, LEFT(genericName, CHARINDEX(',',genericName+',')-1),
    STUFF(genericName, 1, CHARINDEX(',',genericName+','), '')
from eeeee
where LEN(genericName) - LEN(replace(genericName,',','')) < 100
union all
select brandName, LEFT(genericName, CHARINDEX(',',genericName+',')-1),
    STUFF(genericName, 1, CHARINDEX(',',genericName+','), '')
from tmp
where genericName > ''
)
select brandName,  drugList
from tmp
order by brandName

このクエリを実行するのは where 句です。これは、リストに 100 を超える項目がある複数値列の行がいくつかあるためです。SQL Server の 100 の最大再帰制限をこっそりとオーバーライドする方法はありますか? それとも、100 を超える値を持つ列を 2 つに分割して再帰を実行するのが最善でしょうか?

4

1 に答える 1

0

再帰を使用せずに、より効率的なソリューションを提案できます-

DECLARE @temp TABLE
(
      name NVARCHAR(50)
    , properties NVARCHAR(1000)
)

INSERT INTO @temp (name, properties)
VALUES 
    ('x', 'thing1, thing2, thing3'),
    ('y', 'otherthing1, otherthing2, otherthing3')

SELECT  
      data.name
    , property = LTRIM(data.property)
FROM (
    SELECT 
          name = p.value('(./n)[1]', 'NVARCHAR(50)')
        , property = p.value('(./s)[1]', 'NVARCHAR(1000)')
    FROM (
        SELECT field = CAST('<r><s>' + REPLACE(t.properties + ',', ',', '</s><n>' + t.name + '</n></r><r><s>') + '</s></r>' AS XML) 
        FROM @temp t
    ) d
    CROSS APPLY field.nodes('/r') t(p)
) data
WHERE data.name IS NOT NULL

はい、もちろん。テーブル内の各文字列には、固定の区切り文字があります。区切り文字を XML 構造の一部に置き換えます。次のような行が得られます。

thing1, thing2, thing3 -> <r><s>thing1</s><s>thing2</s><s>thing3</s></r>

文字列を XML 日付型に変換し、形成されたツリーを解析します。

<r>
 <s>thing1</s>
 <n>x</n>
</r>
<r>
 <s> thing2</s>
 <n>x</n>
</r>
<r>
 <s> thing3</s>
 <n>x</n>
</r>
于 2013-04-10T09:43:51.513 に答える