SQL - 如何从存储过程中查询临时表?

时间:2015-09-01 15:33:29

标签: sql-server stored-procedures

我创建了一个存储过程,用于创建临时表并插入每月句点。

存储过程:

CREATE PROCEDURE sprPeriod
@Number FLOAT, @end_date DATETIME
AS

BEGIN

IF OBJECT_ID('tempdb..#WorkingDays') IS NOT NULL 
    DROP TABLE #WorkingDays

CREATE TABLE #WorkingDays 
    (Day_Name VARCHAR(10), Day_Nr FLOAT, FromDate DATETIME, ToDate DATETIME)

INSERT INTO 
    #WorkingDays (Day_Name, Day_Nr, FromDate, ToDate)
VALUES 
    ('Monday', -7, DATEADD(mm,-1,DATEADD(dd,1,@end_date)), @end_date),
    ('Tuesday', -6, DATEADD(mm,-1,DATEADD(dd,1,@end_date)), @end_date),
    ('Wednesday', -5, DATEADD(mm,-1,DATEADD(dd,1,@end_date)), @end_date),
    ('Thursday', -4, DATEADD(mm,-1,DATEADD(dd,1,@end_date)), @end_date),
    ('Friday', -3, DATEADD(mm,-1,DATEADD(dd,1,@end_date)), @end_date)

WHILE @Number > 
        (
        SELECT 
            DATEDIFF(mm,MIN(WD.FromDate),MAX(WD.ToDate))+1 
        FROM 
            #WorkingDays WD
        )

    BEGIN 
        INSERT INTO 
            #WorkingDays (Day_Name, Day_Nr, FromDate, ToDate)
        VALUES
            ('Monday', -7, (SELECT DATEADD(mm,-1,MIN(WD.FromDate)) FROM #WorkingDays WD), (SELECT DATEADD(dd, -1,MIN(WD.FromDate)) FROM #WorkingDays WD)),
            ('Tuesday', -6, (SELECT DATEADD(mm,-1,MIN(WD.FromDate)) FROM #WorkingDays WD), (SELECT DATEADD(dd, -1,MIN(WD.FromDate)) FROM #WorkingDays WD)),
            ('Wednesday', -5, (SELECT DATEADD(mm,-1,MIN(WD.FromDate)) FROM #WorkingDays WD), (SELECT DATEADD(dd, -1,MIN(WD.FromDate)) FROM #WorkingDays WD)),
            ('Thursday', -4, (SELECT DATEADD(mm,-1,MIN(WD.FromDate)) FROM #WorkingDays WD), (SELECT DATEADD(dd, -1,MIN(WD.FromDate)) FROM #WorkingDays WD)),
            ('Friday', -3, (SELECT DATEADD(mm,-1,MIN(WD.FromDate)) FROM #WorkingDays WD), (SELECT DATEADD(dd, -1,MIN(WD.FromDate)) FROM #WorkingDays WD))
    END 

END;

然后我尝试以下方法:

EXEC sprPeriod '12', '31 July 2015'    
SELECT * FROM #WorkingDays 

但收到以下错误:

Msg 208, Level 16, State 0, Line 2
Invalid object name '#WorkingDays'.

我不确定为什么无法检索临时数据库。我已经尝试删除DROP TABLE部分,但我故意将它放在循环之前,所以它没有错误地删除它。

为了查询临时数据库,我需要更改什么?

2 个答案:

答案 0 :(得分:3)

过程结束时,将自动删除在过程内创建的临时表。如果需要在程序外部使用表,则必须在调用过程之前创建表,或者需要在过程中使用select返回数据并使用insert into #xxx exec procedurename。

答案 1 :(得分:1)

问题出在您的SELECT查询中,如下所示。您无法访问存储过程范围之外的本地临时表,因为它不再存在。如果您确实想要访问,请考虑使用Global temporary table##WorkingDays

形式的non temporary persistent table
EXEC sprPeriod '12', '31 July 2015'    
SELECT * FROM #WorkingDays // Here