设置SQL Server存储过程的默认参数

时间:2017-09-14 16:30:15

标签: sql sql-server datetime parameters

我正在尝试将@Day的默认值设置为当天。但是,我在初始DATEADD(Day, DATEDIFF(Day, 0, GETDATE()), 0)和其下方的所有@Day上收到了一些错误。我认为alter procedure下的@Day DateTime声明了@Day,但我收到了错误:

  

必须声明标量变量“@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

由于

1 个答案:

答案 0 :(得分: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