Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can't set default value of datetime parameter in stored procedure = getDate()?

I want to know why I can't set default value to SP datetime parameter to getdate() as below :

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

if I try to save it will give me a compiler error

    Msg 102, Level 15, State 1, Procedure UPILog, Line XX
    Incorrect syntax near '('.

EDIT : I know that i can do it like below

Create PROCEDURE [dbo].[UPILog]
(
    @UserID bigint,
    @ActionID smallint,
    @Details nvarchar(MAX) = null,
    @Created datetime = null
)
AS
if @Created is null
    SET @Created=getdate() ...
like image 236
Amr Badawy Avatar asked Jun 19 '10 10:06

Amr Badawy


4 Answers

  ....     
  @CreateDate datetime = null
)

And then use COALESCE() like below -

COALESCE(@CreateDate, getdate())
like image 104
toothful Avatar answered Oct 02 '22 17:10

toothful


If you want to use the @Created as a default though, then set null as the default parameter value and set the @Created parameter with getdate() if it comes with null in your sp.

    ...
    @CreateDate datetime = null
)
AS
    if @CreateDate is null
        set @CreateDate = getdate()
...

EDIT: There is also the documentation explanation: https://stackoverflow.com/a/53832983/197652

like image 45
Emre Guldogan Avatar answered Oct 02 '22 15:10

Emre Guldogan


You can't use a function call as a default parameter value.

It's easy to work around: set your calling parameter to getdate() if not set.

like image 23
Mitch Wheat Avatar answered Oct 02 '22 15:10

Mitch Wheat


in simplest terms it has to be some constant value and GetDate() is a function call.

like image 22
TheVillageIdiot Avatar answered Oct 02 '22 16:10

TheVillageIdiot