ALTER FUNCTION myFun(@theDate Datetime)
RETURNS @myFun TABLE
    (
         服务部 int primary key,
         A佣金 float,
         B佣金 float
    )
AS
begin        declare @tempA table
     (
         服务部 int primary key ,
         A佣金 float  
     )
        
    declare @tempB table
     (
         服务部 int primary key ,      
         B佣金 float    
     ) 
    
     insert  @tempA 
          select 服务部,sum(费用-待收) AS A佣金
           from   成交表 
           where  成交日期=@theDate
                and user='A'
         group by 服务部     insert @tempB
         select 服务部,sum(费用-待收) AS B佣金
          from   成交表 
          where  成交日期=@theDate
               and user='B'
         group by 服务部  
         insert @myfun (select @tempA.*, @tempB.B佣金  
                     from  @tempA ,@tempB  
                     where @tempA.服务部=@tempB.服务部 order by @tempA.服务部 ) 
  
     return
     end /*******************************************************
  其中tempA 和tempB 都可以分别执行 下面的sql语句得到
   select 服务部,sum(费用-待收) AS A佣金
           from   成交表 
           where  成交日期=@theDate
                and user='A'
         group by 服务部    ------------------------------------
         select 服务部,sum(费用-待收) AS B佣金
          from   成交表 
          where  成交日期=@theDate
               and user='B'
         group by 服务部  ----------------------------------------------------
  问题就处在这些代码里面
 insert @myfun (select @tempA.*, @tempB.B佣金  
                     from  @tempA ,@tempB  
                     where @tempA.服务部=@tempB.服务部 order by @tempA.服务部 ) 
这个地方总是提示错误
“ 消息 156,级别 15,状态 1,过程 myFun,第 70 行
关键字 'select' 附近有语法错误。
消息 137,级别 15,状态 2,过程 myFun,第 70 行
必须声明标量变量 "@tempA"。”-----------------------------
这是为什么呢?难道是@tempA这样的table变量不能出现在    from 子句中吗??请教高手!
-----------------------
谢谢!!*/ 
  

解决方案 »

  1.   

    insert @myfun (select @tempA.*, @tempB.B佣金  
                        from  @tempA ,@tempB  
                        where @tempA.服务部=@tempB.服务部 order by @tempA.服务部 ) 
    -->
        insert @myfun select a.*, b.B佣金  
                        from  @tempA a,@tempB b 
                        where a.服务部=b.服务部 order by a.服务部
      

  2.   

    1.@tempA /@tempB 之类的不能作为表的别名,因为以@开头的都会被自动解析为变量,
    2.insert table select * from ...之间没有括号.
      

  3.   

     insert @myfun (select @tempA.*, @tempB.B佣金  
                        from  @tempA ,@tempB  
                        where @tempA.服务部=@tempB.服务部 order by @tempA.服务部 ) 
      
    不要用括号
    语法错误declare @tb table(a int, b int)
    insert into @tb (select 1,2)--impossible
    declare @tb table(a int, b int)
    insert into @tb select 1,2--just do it