查询树型表函数的问题,崩溃啊

yunhaiC QQ654777694 2011-03-21 02:51:44

CREATE function f_pid1(@id int,@tablename varchar(30)) returns varchar(100)
as
begin
declare @re_str as varchar(100)
set @re_str = ''
select @re_str = name from @tablename where id = @id
while exists (select 1 from @tablename where id = @id and pid is not null)
begin
select @id = b.id , @re_str = b.name + ',' + @re_str from @tablename a , @tablename b where a.id = @id and a.pid = b.id
end
return @re_str
end


他说我没声明@tablename,这个是传过来的参数啊,郁闷,到底怎么改,也有网友说用exec动态执行,但是我改来改去还是有bug,请教啊

CREATE function f_pid1(@id int,@tablename varchar(20)) returns varchar(100)
as
begin
declare @re_str as varchar(100)
set @re_str = ''
exec('select '+@re_str+' = name from '+@tablename+' where id = '+rtrim(@id))
exec('while exists (select 1 from tb where id = '+rtrim(@id)+' and pid is not null)
begin
select '+rtrim(@id)+' = b.id , '+@re_str+' = b.name + '','' + '+@re_str+' from '+@tablename+' a , tb b where a.id = '+rtrim(@id)+' and a.pid = b.id
end')
return @re_str
end
...全文
92 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
wokelv 2011-05-13
  • 打赏
  • 举报
回复
>>>> 函数里没法执行动态

那数据库里的 内部函数(Avg, Sum, Count等)怎么实现的..
求解..
  • 打赏
  • 举报
回复
至今没有完全解决
xiangchao107 2011-03-21
  • 打赏
  • 举报
回复
有高手解决了没有啊,正需要这方面的东西
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 acherat 的回复:]

存储过程也可以加参数!
[/Quote]

create Procedure f_pid1
@id int,
@tablename varchar(30),
@re_str varchar(100) output
as
begin
set @re_str = ''
select @re_str = name from @tablename where id = @id
while exists (select 1 from @tablename where id = @id and pid is not null)
begin
select @id = b.id , @re_str = b.name + ',' + @re_str from @tablename a , @tablename b where a.id = @id and a.pid = b.id
end
end

还是不行
AcHerat 2011-03-21
  • 打赏
  • 举报
回复
存储过程也可以加参数!
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xiao_ai_mei 的回复:]

函数里没法执行动态
改存储过程吧
[/Quote]
但是我可能有其他表也需要用这个功能,我不能每次都要根据各个表写同样的功能啊,所以还是需要放在函数里面
Xiao_Ai_Mei 2011-03-21
  • 打赏
  • 举报
回复
函数里没法执行动态
改存储过程吧

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧