一、新建表
create table NewCategories (
ID int IDENTITY(1,1) primary key,
ParentID int null,
Name nvarchar(max)
)
现在,将所有行插入新表(这将分配 ID)
insert into NewCategories (Name)
select distinct CategoryName
from OldCategories
insert into NewCategories (Name)
select distinct SubCategoryName
from OldCategories
insert into NewCategories (Name)
select distinct SubSubCategoryName
from OldCategories
更新NewCategories
表,设置 ParentID 列,一次用于SubCategoryName
,一次用于SubSubCategoryName
:
update nc2
set ParentID = nc1.ID
from NewCategories nc1
inner join OldCategories oc on oc.CategoryName = nc1.Name
inner join NewCategories nc2 on oc.SubCategoryName = nc2.Name
update nc2
set ParentID = nc1.ID
from NewCategories nc1
inner join OldCategories oc on oc.SubCategoryName = nc1.Name
inner join NewCategories nc2 on oc.SubSubCategoryName = nc2.Name
*CategoryName
这假定原始表中没有重复项。
SQL小提琴
对于重复项,您可以执行(稍微复杂一些)
--insert all categories
insert into NewCategories (Name)
select distinct CategoryName
from OldCategories
--only categories in the "new" table now
insert into NewCategories (ParentID, Name)
select distinct n.ID, o.SubCategoryName
from OldCategories o
inner join NewCategories n on o.CategoryName = n.Name
--now subcategories are items with non-null parents,
-- so we need a double join
insert into NewCategories (ParentID, Name)
select distinct n1.ID, o.SubSubCategoryName
from OldCategories o
inner join NewCategories n1 on o.SubCategoryName = n1.Name
inner join NewCategories n2 on o.CategoryName = n2.Name and n2.ID=n1.ParentID
这是一个新的小提琴,修改为处理重复