为什么我们不能在stored procedure = getDate()中设置datetime参数的默认值?

Amr*_*awy 10 stored-procedures sql-server-2005

我想知道为什么我不能将SP datetime参数的默认值设置为getdate(),如下所示:

Create PROCEDURE [dbo].[UPILog]
(
    @UserID bigint,
    @ActionID smallint,
    @Details nvarchar(MAX) = null,
    @Created datetime = getdate()
)
Run Code Online (Sandbox Code Playgroud)

如果我尝试保存它会给我一个编译器错误

    Msg 102, Level 15, State 1, Procedure UPILog, Line XX
    Incorrect syntax near '('.
Run Code Online (Sandbox Code Playgroud)

编辑: 我知道我可以像下面这样做

Create PROCEDURE [dbo].[UPILog]
(
    @UserID bigint,
    @ActionID smallint,
    @Details nvarchar(MAX) = null,
    @Created datetime = null
)
AS
if @Created is null
    SET @Created=getdate() ...
Run Code Online (Sandbox Code Playgroud)

Emr*_*gan 18

如果你想使用@Created作为默认值,那么将null设置为默认参数值,如果你的sp中带有null,则将@Created参数设置为getdate().

    ...
    @CreateDate datetime = null
)
AS
    if @CreateDate is null
        set @CreateDate = getdate()
...
Run Code Online (Sandbox Code Playgroud)


Mit*_*eat 5

您不能使用函数调用作为默认参数值。

解决方法很简单:将调用参数设置为getdate()(如果未设置)。

  • @SpaceCracker我相信的原因是你要做的(如果允许的话)是在编译代码时运行 getdate() 函数(请记住我们正在编译代码)并存储将 getdate() 运行一次的结果作为默认值...您不想要的东西。您想要的是让它在调用 UPILog 函数时运行 getdate 函数,这应该/只能在函数体中完成。 (2认同)