SQL HierarchyID数据类型,如何生成OrgNode以便快速插入

时间:2013-11-18 21:58:04

标签: sql sql-server

我正在考虑将父子层次结构表更改为hierarchyid数据类型, 我正在寻找T-sql querty(我猜它将用CTE实现),它将帮助我生成新节点并将它们插入hierarchyid表 我有七个固定级别,我可以逐个运行,并找到每个级别的所有新节点。 现在,问题在于我需要在不使用内联函数或游标的情况下插入它,因为成员数量很大(在低级别大约1Mil)。 我有一个查询返回需要与父项一起插入的所有新节点 意思是:我有@parentOrgNode hierarchyID,@ NewCustomerCode varchar(255)的列表 例如:需要插入的新节点(级别4)列表

select distinct  C1.orgNode as ParentCode,S.PH1_LVL4_NAME,S.PH1_LVL4_CODE
from [Staging].[dbo].[CustomerHierarchy] S
inner join customer C1 on C1.CustomerCode=PH1_LVL3_CODE
left outer join Customer C2 on C2.CustomerCode=PH1_LVL4_CODE
where C2.CustomerCode is null

对于每个返回行,需要生成OrgNode以插入到Customer表中 感谢

1 个答案:

答案 0 :(得分:0)

说你有下表

create table customer_hierarchy (
    customer_id int not null constraint pk_customer_hierarchy primary key,
    parent_customer_id int references customer_hierarchy
);

您可以通过以下几种方式生成层次结构。第一个使用层次结构中的现有ID。第二个将它们折叠成连续的整数:

with cte as (
    select
        '/' + cast(h.customer_id as nvarchar(3998)) + '/' as pos,
        customer_id
    from
        customer_hierarchy h
    where
        h.parent_customer_id is null
    union all
    select
        pos + cast(h.customer_id as nvarchar(3998)) + '/',
        h.customer_id
    from
        cte c
            inner join
        customer_hierarchy h
            on h.parent_customer_id = c.customer_id
) select
    cast(pos as hierarchyid) pos,
    customer_id
from
    cte

使用row_number()

with cte as (
    select
        '/' + cast(
            row_number() over (order by customer_id) as nvarchar(3998)
        ) + '/' as pos,
        customer_id
    from
        customer_hierarchy h
    where
        h.parent_customer_id is null
    union all
    select
        pos + cast(
            row_number() over (
                partition by c.customer_id 
                order by h.customer_id
            ) as nvarchar(3998)
        ) + '/',
        h.customer_id
    from
        cte c
            inner join
        customer_hierarchy h
            on h.parent_customer_id = c.customer_id
    ) select
        cast(pos as hierarchyid),
        customer_id
    from
        cte