分类:
2008-10-15 16:52:08
CREATE function getUserTree(@UserName sysname, --用户名 @Seq bit --查找方式:0查找子孙 1.查找祖先 ) returns @Result table(UserID sysname,UserName sysname,Level int) as begin declare @UserId sysname set @userId=user_id(@userName) if @userid is null begin --raiserror(´指定的用户名不存在´,16,1) return end DECLARE @level int, @line char(20) declare @stack table(item sysname, level int) INSERT INTO @stack VALUES (@UserID, 1) SELECT @level = 1 WHILE @level > 0 BEGIN IF EXISTS (SELECT * FROM @stack WHERE level = @level) BEGIN SELECT @userId = item FROM @stack WHERE level = @level insert into @Result values(@UserId,User_name(@userID),@level) DELETE FROM @stack WHERE level = @level AND item = @userId if @Seq=1 --查找祖先 INSERT @stack SELECT groupuid, @level + 1 FROM sysmembers WHERE memberuid = @userId else --查找子孙 INSERT @stack SELECT memberuid, @level + 1 FROM sysmembers WHERE groupuid = @userId IF @@ROWCOUNT > 0 SELECT @level = @level + 1 END ELSE SELECT @level = @level - 1 END -- WHILE return end