SQL function as default parameter value?

前端 未结 6 413
孤城傲影
孤城傲影 2020-12-13 11:45

I tried changing a default parameter value with this:

ALTER PROCEDURE [dbo].[my_sp]
@currentDate datetime = GETDATE()

and all the SQL pre-c

相关标签:
6条回答
  • 2020-12-13 12:05

    I infer you're using Microsoft SQL Server from the square brackets in your example.

    From MSDN:

    Only a constant value, such as a character string; a scalar function (either a system, user-defined, or CLR function); or NULL can be used as a default.

    The function GETDATE() returns a different value from time to time, so it is not a constant expression.

    0 讨论(0)
  • 2020-12-13 12:10

    You can try as follow:

    Set @CurrentDate=IsNull(@CurrentDate,GetDate())
    
    0 讨论(0)
  • 2020-12-13 12:20

    That value is not deterministic and cannot be used

    0 讨论(0)
  • 2020-12-13 12:20

    Suggestion:

    Set the default to NULL

    Do the Default GETDATE() in the front end.

    0 讨论(0)
  • 2020-12-13 12:28

    I don't think that is possible, you have to use a literal (constant) value as the default.

    However you can do this:

    Set @currentDate = Coalesce(@currentDate , GetDate())
    
    0 讨论(0)
  • 2020-12-13 12:30

    Default value for stored procedures parameter have to be constants. You'd need to do the following...

    ALTER Procedure [dbo].[my_sp]
    @currentDate datetime = null
    AS
    IF @currentDate is null
    SET @currentDate = getdate()
    
    0 讨论(0)
提交回复
热议问题