SQL Server树型结构数据处理的存储过程

我们在平常的系统开发中常常会遇到像无限级分类这样的树型结构数据,现提供一个可用的数据库存储过程,可以完成树型结构数据的排序。

环境:windows7+Sql Server 2008

说明:下面代码已经转换成Sql server2000的脚本,处理效果如下,看sortname字段结果,代码经过测试。

SQL Server树型结构数据处理的存储过程

创建树型表

  
    
CREATE TABLE [ dbo ] . [ categories ] (
[ category_id ] [ int ] IDENTITY ( 1 , 1 ) NOT NULL ,
[ parent_id ] [ int ] NULL ,
[ category_name ] [ varchar ] ( 500 ) NULL ,
CONSTRAINT [ PK_categories ] PRIMARY KEY CLUSTERED
(
[ category_id ] ASC
)
ON [ PRIMARY ]
)
ON [ PRIMARY ]
GO

插入测试数据

  
    
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 1 , 0 , CONVERT ( TEXT , N ' A ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 2 , 0 , CONVERT ( TEXT , N ' B ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 3 , 1 , CONVERT ( TEXT , N ' AA ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 4 , 3 , CONVERT ( TEXT , N ' AAA ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 5 , 2 , CONVERT ( TEXT , N ' BB ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 6 , 1 , CONVERT ( TEXT , N ' AA2 ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 7 , 1 , CONVERT ( TEXT , N ' AA3 ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 8 , 3 , CONVERT ( TEXT , N ' AAA2 ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 9 , 4 , CONVERT ( TEXT , N ' AAA3 ' ))
INSERT [ dbo ] . [ categories ] ( [ category_id ] , [ parent_id ] , [ category_name ] ) VALUES ( 10 , 2 , CONVERT ( TEXT , N ' BB2 ' ))

创建存储过程,表中的level为级别深度,通过生成的临时表与分类表关联显示结果。

  
    
CREATE PROCEDURE [ dbo ] . [ Get_TreeData ]
AS
BEGIN
-- 创建临时表
create table #tmp_table (id int , [ level ] int )

declare @LevelValue int
set @LevelValue = 0
insert #tmp_table select 0 , @LevelValue
-- 将数据写入到临时表
while @@rowcount > 0
begin
set @LevelValue = @LevelValue + 1
insert #tmp_table select a.category_id, @LevelValue
from categories as a,#tmp_table as b
where a.parent_id = b. [ id ] and b. [ level ] = @LevelValue - 1
end
-- select * from #tmp_table
select a.category_id,a.parent_id,a.category_name,b. [ level ] ,
case
when a.parent_id = 0 then a.category_name else replicate ( ' - ' ,b. [ level ] ) + a.category_name
end as sortname
from categories as a join #tmp_table as b on a.category_id = b.id
order by sortname
return
END

 

你可能感兴趣的:(SQL Server)