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

解决方案 »

  1.   


    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还是不行
      

  2.   

     >>>> 函数里没法执行动态那数据库里的  内部函数(Avg, Sum, Count等)怎么实现的..
    求解..