存储过程返回具有层级关系Json字符串
这段时间学习EasyUI combotree,需要提供层级的jeson格式数据,想到能否在存储过程中查好数据,并组合成json格式字符串返回,经过试验是可以的,但本人是初学者,本想做成通用的可传入层级相关字段名的方法,但没有实现,请看到程序的网友帮我改正,也请指出存储过程中不对的地方,谢谢。
表名称为menu,其结构如图:

存储过程代码如下:
create proc [dbo].[GetLevelJson]
@id int, --传入需要返回的id
@resustJson nvarchar(4000) output --输出json结果
as
begin
declare @tempId int
declare @text varchar(50)
set @tempId=0
declare cur cursor LOCAL FOR select id,[text] from menu where pid= @id
open cur
fetch next from cur into @tempId,@text
if(@tempId>0)
begin
set @resustJson='['
while @@fetch_status=0
begin
set @resustJson=@resustJson+'{"id":"'+rtrim(cast(@tempId as char))+'","text":"'+@text+'"'
if((select count(*) from menu where pid=@tempId)>0)
begin
declare @tempstr nvarchar(1000)
exec GetLevelJson @tempId,@tempstr output
set @resustJson=@resustJson+',"children":'+@tempstr
end
set @resustJson=@resustJson+'},'
fetch next from cur into @tempId,@text
end
close cur
deallocate cur
set @resustJson=substring(@resustJson,0,len(@resustJson))
set @resustJson=@resustJson+']'
end
end

浙公网安备 33010602011771号