CREATE FUNCTION  getTitle   ( @tablename VARCHAR(100) ,@topicid INT )  
RETURNS  VARCHAR(200)   AS  
BEGIN 
DECLARE  @Estr   VARCHAR(500) 
SET @Estr=N'select title  from '+@tablename+' where topicid='+ Convert(Varchar(10),@topicid)
sp_EXECUTEsql(@Estr)//好象不能这样用!!!!报错!
             return //我想返回 title字段的内容,title 是varchar类型的
END

解决方案 »

  1.   

    CREATE FUNCTION  getTitle   ( @tablename VARCHAR(100) ,@topicid INT )  
    RETURNS  VARCHAR(200)   AS  
    BEGIN 
    DECLARE  @Estr   VARCHAR(500) 
    SET @Estr='select title  from '+@tablename+' where topicid='+ Convert(Varchar(10),@topicid)
    --EXECUTE(@Estr)--好象不能这样用!!!!报错!
                 return(@Estr) --我想返回 title字段的内容,title 是varchar类型的
    END
      

  2.   

    CREATE FUNCTION  getTitle   ( @tablename VARCHAR(100) ,@topicid INT )  
    RETURNS  VARCHAR(200)   AS  
    BEGIN 
    DECLARE  @Estr   NVARCHAR(500) 
            DECLARE  @return   VARCHAR(500) 
    SET @Estr='select @return=title  from '+@tablename+' where topicid='+ Convert(Varchar(10),@topicid)
            exec sp_executesql @Estr,N'@return varchar(500) output',@return output

                 return @return  
    END
      

  3.   

    各位老大,还是不行呀!!!!
    报错
    Only functions and extended stored procedures can be executed from within a function.
      

  4.   


    执行的时候应该 dbo.getTitle('tableName', 'ID')
      

  5.   

    还是报错呀,各位,多谢
    服务器: 消息 557,级别 16,状态 2,过程 getTitle,行 11
    Only functions and extended stored procedures can be executed from within a function.
      

  6.   

    用游标吧
    declare @tb_name varchar(20)
    declare @sql varchar(4000)
    declare cur cursor for
    select distinct atTable from bbsbak
    open cur
    fetch next from cur 
    into @tb_name 
    set @sql=''
    while(@@fetch_status=1)
    begin
     @sql=@sql+' select title from '+@tb_name+' union '
     fetch next from cur 
     into @tb_name 
    endset @sql=left(@sql,len(@sql)-6) 
    go
    print (@sql) 
    go
    exec(@sql)