日期:2014-05-18  浏览次数:20420 次

问个存储过程的小问题
在存储过程里面建立了个表 @table,然后写了一个@sql,就是一个执行语句,
然后 exec(@sql),结果报错,说@table为声明。。。。

这是怎么回事呢?我明明声明了啊

------解决方案--------------------
SQL code


ALTER PROCEDURE [dbo].[spInventoryAge]
    -- Add the parameters for the stored procedure here
    @whID int = 0 ,
    @ageOne smallint =30,
    @ageTwo smallint =60,
    @ageThree smallint =90
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    create table #inventoryAge 
    (
        whID int,
        whName nvarchar(30),
        placeID smallint,
        placeName nvarchar(30),
        resourceID int,
        resourceName nvarchar(198),
        quantity decimal(18,4),
        ageStage1 decimal(18,4),
        ageStage2 decimal(18,4),
        ageStage3 decimal(18,4),
        ageStage4 decimal(18,4)
    )
    
    create table #MaterialAge 
    (
        resourceID int,
        resourceName nvarchar(198),
        quantity decimal(18,4),
        ageStage smallint
    )
    
    declare @currentDate datetime
    set @currentDate=GETDATE()
    
    insert into #inventoryAge
        select I.whID,w.whName,I.placeID,I.placeName,I.resourceID,I.resourceName,
               I.quantity,0,0,0,0
        from dbo.vwInventory as I inner join
             dbo.Warehouse as W on I.whID=W.whID
    
    insert into #MaterialAge
        select EI.resourceID,EI.resourceName,sum(EI.quantity) as quantity,EI.ageStage
        from 
        (
                select   
                     WI.resourceID,WI.resourceName,wi.quantity, 
                     case when @currentDate-W.entryDate<@ageOne then 1
                     when @currentDate-W.entryDate<@ageTwo then 2
                     when @currentDate-W.entryDate<@ageThree then 3
                     else 4  end as ageStage 
                from    
                     dbo.vwWarehouseEntryItem as WI inner join
                     dbo.WarehouseEntry as W ON W.entryID=WI.entryID
        ) EI
        group by EI.resourceID,EI.resourceName,EI.ageStage
    
    declare @updateSql varchar(max)
             
    set @updateSql='';
    select @updateSql=@updateSql+' ageStage'+LTRIM(M.ageStage)
           +'=max(case when ageStage='+LTRIM(M.ageStage)+' then quantity else 0 end)'
        from @MaterialAge as M group by M.ageStage
    --打印出来看看   
    print @updateSql
    exec('update @#inventoryAge set '+@updateSql+' 
          from @MaterialAge group by resourceID,resourceName')

    set nocount off;