2017-09-14 116 views
1

我試圖將默認值@Day設置爲當天。但是,我在初始DATEADD(Day, DATEDIFF(Day, 0, GETDATE()), 0)和其下的所有@Day s上遇到了一些錯誤。我認爲@Day DateTime下的ALTER過程中聲明@Day但我得到的錯誤:設置SQL Server存儲過程的默認參數

Must declare the scalar variable "@Day"

任何人都知道該怎麼辦?

ALTER PROCEDURE [dbo].[InsertWeeklyRuns] 
    @Day DateTime = DATEADD(Day, DATEDIFF(Day, 0, GETDATE()), 0) 
AS 
BEGIN 
    SET NOCOUNT ON 

    DECLARE @Enddate DATETIME 
    DECLARE @StartDate DATETIME 
    DECLARE @F1Runs INT 
    DECLARE @F2Runs INT 
    DECLARE @F3Runs INT 
    DECLARE @F1Alarms INT 
    DECLARE @F2Alarms INT 
    DECLARE @F3Alarms INT 

    SET @Day = DATEADD(dd, DATEDIFF(dd, 0, @Day), 0) 

    SET @Enddate = CASE 
         WHEN @Day > DATEADD(Day, DATEDIFF(Day, 0, GETDATE()), 0) 
         THEN DATEADD(Day, DATEDIFF(Day, 0, GETDATE()), 0) 
         ELSE DATEADD(Day, 1, @Day) 
        END 

    SET @StartDate = @Enddate - 7 

感謝

+0

有些東西似乎有點過這裏。你正在設置你的變量,然後用case表達式檢查它的值。既然你只是設置它,使用case表達式沒有意義,它總是會返回第一個值。 –

+0

您不能指定一個不確定的默認值(例如'getdate()'或其任何變體)。相反,將默認設置爲「null」。然後在你的proc體內,如果'@ day'爲空,將它設置爲你想要的默認值。 'select @Day = isnull(@day,cast(getdate()as date))' – Xedni

+0

@SeanLange All'Set @Day = DATEADD(dd,DATEDIFF(dd,0,@Day),0)從任何'@ Day'設定的時間。例如,如果某人設置了「@Day = 5/20/16 4:57」,則「@Day =設置@Day = DATEADD(dd,DATEDIFF(dd,0,@Day),0)'將帶走4: 57。如果'@ Day'被設置爲將來的某一天,案例陳述就會發揮作用。 – MadelineK

回答

0

這應該是你所期望的工作:

CREATE PROCEDURE [dbo].[InsertWeeklyRuns] 
    @Day DateTime 
AS 
BEGIN 

SET NOCOUNT ON 

Declare @Enddate Datetime 
Declare @StartDate Datetime 
Declare @F1Runs Int 
Declare @F2Runs Int 
Declare @F3Runs Int 
Declare @F1Alarms Int 
Declare @F2Alarms Int 
Declare @F3Alarms Int 
DECLARE @today date = CAST(GETDATE() AS date); 

IF @Day IS NULL 
    Set @Day = @today 

Set @Enddate = CASE WHEN @Day >= @today THEN @today ELSE DATEADD(Day, 1, @Day) END 

Set @StartDate = @Enddate - 7 
END