如何循环sql server中的分层列?

时间:2014-08-29 16:56:58

标签: sql-server cursor

我有一个表定义客户的层次结构table1(id,country,state,region,...)。另一个表包含每个客户的一些数据(id,data1,data2,...)。我需要使用存储过程以下列格式生成报告:

Detail report of each customer under country 01-state 01-region 01
Summary of country 01-state 01-region 01

Detail report of each customer under country 01-state 01-region 02
Summary of country 01-state 01-region 02
…
Detail report of each customer under country 01-state 01-region 0x
Summary of country 01-state 01-region 0x

Summary of country 01-state01

Detail report of each customer under country 01-state 03-region 01
Summary of country 01-state 01-region 01

Detail report of each customer under country 01-state 03-region 04
Summary of country 01-state 01-region 02
…
Detail report of each customer under country 01-state 03-region 0x
Summary of country 01-state 01-region 0x

Summary of country 01-state02
…

Summary of country 01

目前我使用游标循环遍历层次结构(国家,州,地区)并进行一些计算以生成报告,因为我们有数百万条记录,所以性能不是很好。以下是我的存储过程的结构。

declare @country_cursor cursor  
set @country_cursor =cursor local scroll for 
    select distinct country
    from table1
    order by country
open @country_cursor
fetch next from country_cursor into @country
while @@fetch_status=0
begin --country
    declare @state_cursor cursor 
    set @state_cursor =cursor local scroll for 
        select distinct state
        from table1
        where country=@country
        order by state
    open @state_cursor
    fetch next from @state_cursor into @state
    while @@fetch_status=0
    begin --state
        declare @region_cursor cursor 
        set @region_cursor =cursor local scroll for 
            select distinct region
            from table1
            where county=@country and state=@state
            order by region
        open @region_cursor
        fetch next from @region_cursor into @region
        while @@fetch_status=0
        begin --region
              print '--customers--'
            … (some calculation)

            print '--region summary--'
            ...(some calculation)
            fetch next from @region_cursor into @region
        end--region

        print '--state summary--'
        …
        deallocate @state_cursor
        fetch next from @state_cursor into @state
    end—state

    print '--country summary--'
      …
    deallocate @country_cursor
    fetch next from @country_cursor into @country
end--country

我的问题是否有任何其他方法可以用来替换光标以提高性能?我想到了while循环,但我不确定如何使用while循环遍历层次结构。并且while循环比光标更好吗?

0 个答案:

没有答案