この混乱により、サンプル データからサンプル結果が生成されます。アルゴリズムがどうあるべきかはまだ明確ではありません。
declare @CategoryItems as Table (
CategoryName NVarChar(255),
Label NVarChar(255),
ProductId Int,
ChildCategoryId Int,
CategoryId Int );
declare @Categories as Table (
CategoryId Int,
Name NVarChar(100) );
insert into @CategoryItems ( CategoryName, Label, ProductId, ChildCategoryId, CategoryId ) values
( 'CategoryA', 'Widget A', 1, 0, 1 ),
( 'CategoryB', 'CategoryA', 0, 1, 2 ),
( 'CategoryC', 'Widget B', 2, 0, 3 );
insert into @Categories ( CategoryId, Name ) values
( 1, 'CategoryA' ),
( 2, 'CategoryB' ),
( 3, 'CategoryC' );
select * from @Categories;
select * from @CategoryItems;
declare @TargetProductId as Int = 1;
with Leonard as (
-- Start with the target product.
select 1 as [Row], ProductId, Label, CategoryId, ChildCategoryId
from @CategoryItems
where ProductId = @TargetProductId
union all
-- Add each level of child category.
select L.Row + 1, NULL, CI.Label, CI.CategoryId, CI.ChildCategoryId
from @CategoryItems as CI inner join
Leonard as L on L.CategoryId = CI.ChildCategoryId ),
Gertrude as (
-- Take everything that makes sense.
select Row, ProductId, Label, CategoryId, ChildCategoryId
from Leonard
union
-- Then tack on an extra row for good measure.
select L.Row + 1, NULL, C.Name, NULL, C.CategoryId
from Leonard as L inner join
@Categories as C on C.CategoryId = L.CategoryId
where L.Row = ( select Max( Row ) from Leonard ) )
select Row, ProductId, Label, CategoryId, ChildCategoryId
from Gertrude
order by Row;
問題は、偏った方法でデータを混合したことだと思います。カテゴリの階層は通常、次のように表されます。
declare @Categories as Table (
CategoryId Int Identity,
Category NVarChar(128),
ParentCategoryId Int Null );
各階層のルートは で示されParentCategoryId is NULL
ます。これにより、任意の数の独立したツリーを 1 つのテーブルに共存させることができ、製品の存在に依存しません。
製品が 1 つの (サブ) カテゴリに割り当てられている場合はCategoryId
、Products
テーブルに を含めます。製品が複数の (サブ) カテゴリに割り当てられている可能性があり、異なる階層にある可能性がある場合は、別のテーブルを使用してそれらを関連付けます。
declare @ProductCategories as Table (
ProductId Int,
CategoryId Int );