我正在尝试创建存储过程,该存储过程将返回行WHERE
在“开始”和“结束”值之间的创建日期。但是我想考虑存储过程为空值的可能性,因此我需要默认值。
CREATE PROCEDURE [dbo].[GetProjectsRatingByCreationDateInterval]
@Start DATETIME = GETDATE,
@End DATETIME = DATEADD(MONTH, -1, GETDATE())
AS
SELECT
ID, ProjectName, Rating, CreationDateTime
FROM
Projects
WHERE
CreationDateTime BETWEEN @Start AND @End
试图这样做,但收到此错误:
'('附近的语法不正确。
它引用DATEADD
声明中的@End
函数调用。
答案 0 :(得分:1)
请将该值设置为Null并在内部程序中进行如下设置
CREATE PROCEDURE [dbo].[GetProjectsRatingByCreationDateInterval]
@Start DATETIME NULL,
@End DATETIME NULL
AS
IF @Start is null
SET @Start = GETDATE()
IF @End is null
SET @End = DATEADD(MONTH, -1, GETDATE())
SELECT
ID, ProjectName, Rating, CreationDateTime
FROM
Projects
WHERE
CreationDateTime BETWEEN @Start and @End
答案 1 :(得分:1)
问题在这里
@Start DATETIME = GETDATE,
getdate是一个函数,因此将其写为GETDATE()
@Start DATETIME = GETDATE(),
过程看起来像这样
CREATE PROCEDURE [dbo].[GetProjectsRatingByCreationDateInterval]
@Start DATETIME = GETDATE(),
@End DATETIME = DATEADD(MONTH, -1, GETDATE())
AS
BEGIN
SELECT
ID, ProjectName, Rating, CreationDateTime
FROM
Projects
WHERE
CreationDateTime BETWEEN @Start AND @End
END
答案 2 :(得分:0)
您可以根据需要使用以下代码。
CREATE PROCEDURE [dbo].[GetProjectsRatingByCreationDateInterval]
@Start DATETIME = CURRENT_TIMESTAMP,
@End DATETIME = NULL
AS
SELECT
ID, ProjectName, Rating, CreationDateTime
FROM
Projects
WHERE
CreationDateTime BETWEEN @Start AND (CASE WHEN @End IS NULL THEN DATEADD(MONTH, -1, @Start) ELSE @End END)
答案 3 :(得分:0)
如果传递的是ISNULL()
,您还可以使用NULL
函数将其默认设置为一个值:
CREATE PROCEDURE dbo.GetProjectsRatingByCreationDateInterval
@Start DATETIME NULL, @End DATETIME NULL
AS
BEGIN
SET @Start = ISNULL(@Start, GETDATE());
SET @End = ISNULL(@Start, DATEADD(MONTH, -1, GETDATE()));
SELECT ID, ProjectName, Rating, CreationDateTime
FROM Projects
WHERE CreationDateTime BETWEEN @Start AND @End;
END;