[原创]分级设计数据表存储过程查询子级数据

--根据当前ID,获取其子级数据 @ID:当前ID,@TableName:表名,@f_id:主键列名,@f_parentid:父级ID列名,@isthis:是否列出当前ID
create proc [dbo].[proc_GetChildLevel](@ID varchar(10),@TableName varchar(20),@f_id varchar(10),@f_parentid varchar(10),@isthis bit)  
as  
begin

	declare @sql varchar(max)
	set @sql=
	'declare @t table(ID varchar(10),ParentID varchar(10),ThisLevel int)
	declare @i int
    set @i = 1
	if('+convert(varchar(5),@isthis)+'=1)
	begin
		insert into @t select '+@ID+','+@ID+',0 --当前级,本级,如果不要的话可以注释掉或再加个参数来选择操作
	end
	insert into @t select '+@f_id+','+@f_parentid+',@i from '+@TableName+' where '+@f_parentid+' = '+@ID+'

    while @@rowcount<>0  
    begin  
        set @i = @i + 1
		insert into @t select a.'+@f_id+',a.'+@f_parentid+',@i from '+@TableName+' a,@t b where a.'+@f_parentid+'=b.ID and b.ThisLevel = @i-1
    end
    select a.ThisLevel,b.* from @t a left join '+@TableName+' b on a.ID=b.'+@f_id

	exec(@sql)
end
posted @ 2014-10-30 17:32  代码啦  阅读(138)  评论(0)    收藏  举报