数据库递归 (省级用户可以查看省级下市级以及县级的用户)

用到了函数


GO
/****** 对象: UserDefinedFunction [dbo].[GetChild] 脚本日期: 10/07/2014 10:41:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[GetChild](@ID varchar(10))
returns @t table(ID varchar(10),ParentID varchar(10),Level int)
as
begin
declare @i int
set @i = 1
insert into @t select @ID,@ID,0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作
insert into @t select ID,PersonId,@i from AuthorityUser where PersonId = @ID

while @@rowcount<>0
begin
set @i = @i + 1
insert into @t
select
a.ID,a.PersonId,@i
from
AuthorityUser a,@t b
where
a.PersonId=b.ID and b.Level = @i-1
end
return
end

如何使用这个函数

select ID from dbo.GetChild(3) 3--指的是省级的用户id

 

posted @ 2014-10-07 10:46  牡丹  阅读(231)  评论(0)    收藏  举报