再帰的なテーブルの文字列を連結する
例えば、
create table TextTable( TextId integer not null, Text varchar(100), NextId integer, primary key(TextId), foreign key(NextId) references TextTable(TextId), );
こんな風に、再帰的になっている、単方向リンクリストのようなテーブルがあって、
TextId | Text | NextId |
---|---|---|
0 | あいうえお | 2 |
1 | かきくけこ | null |
2 | さしすせそ | 1 |
こういう値が入っているときに、TextId = 0 の位置から順に辿っていき、
[あいうえお][さしすせそ][かきくけこ]
こんな結果を取り出したい場合にはどうすればいいか、というのを考えてみます。
with Temp(TextId, Text, NextId) as ( select A.TextId, A.Text, A.NextId from TextTable as A where A.TextId = '0' union all select A.TextId, A.Text, A.NextId from TextTable as A, Temp as Temp2 where A.TextId = Temp2.NextId ) select Text from Temp;
こんなクエリを書いてやると、
Text |
---|
あいうえお |
さしすせそ |
たちつてと |
で、テーブルにするのではなく、全ての文字列を結合することが目的なので、後はこれを結合してやります。
declare @str0 varchar(4000); set @str0=''; with Temp(TextId, Text, NextId) as ( select A.TextId, A.Text, A.NextId from TextTable as A where A.TextId = '0' union all select A.TextId, A.Text, A.NextId from TextTable as A, Temp as Temp2 where A.TextId = Temp2.NextId ) select @str0=@str0+'['+Text+']' from Temp; select @str0;
これで、正常に文字列が結合されます。
で、これを SqlDataSource にバインドしようとしてみたんですが、どうやら declare とか set とかは出来ないみたい。
なので、これをストアドプロシージャにしてそれをバインドしてやるのが吉かと。
ちなみに使用しているのは SQL Server 2005 Express なので、他の再帰SQL構文がどうなるかはシラナス(´・ω・`)