我已經創建了一個存儲過程,用於創建臨時表並插入每月的時間段。SQL - 如何從存儲過程查詢臨時表?
存儲過程:
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部分,但我故意將它放在循環之前,所以它沒有誤刪。
爲了查詢臨時數據庫,我需要更改什麼?