SQL SERVER 2005,表值函数里面可以写动态SQL吗?因为我的表是不固定的,如2006年的销售数据和2007年的销售数据分别存在sales_2006和sales_2007表中
前提是我一定要用表值函数,我写的如下:CREATE FUNCTION [dbo].[GetSales] 
(
    -- Add the parameters for the function here
    @Year char(4) 
)
RETURNS TABLE 
AS
return
(
    begin
declare @Sql varchar(1000) set @Sql = 'select product,qty,value from sales_' + @Year  exec(@Sql)    end
)编译的时候在declare处老是报语法错误,可以这样写吗?可以在表值函数里写动态SQL吗?
在线等!

解决方案 »

  1.   

    SQL SERVER 2005,表值函数里面可以写动态SQL吗? ---------
    不能
      

  2.   

    --存儲過程不是更簡單
    create proc [GetSales] 
     @Year varchar(10)
    as 
      exec('select product,qty,value from sales_' + @Year ) 
      

  3.   

    CREATE FUNCTION [dbo].[GetSales] 

        -- Add the parameters for the function here 
        @Year char(4) 

    RETURNS @t TABLE(product varchar(32), qty varchar(32), value varchar(32)) 
    AS
    begin
    if @Year='2006'
    insert @t select product,qty,value from sales_2006
    else  
    insert @t select product,qty,value from sales_2006
    return
    end
    go
      

  4.   

    可以用IF ELSE:
    CREATE FUNCTION [dbo].[GetSales] 

        -- Add the parameters for the function here 
        @Year char(4) 

    RETURNS @t TABLE(product varchar(32), qty varchar(32), value varchar(32)) 
    AS
    begin
        if @Year='2006'
            insert @t select product,qty,value from sales_2006
        else  
            insert @t select product,qty,value from sales_2007
        return
    end
    go
      

  5.   


    我有15年的数据,是不是要写15个if else啊?