Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Assign default DateTime value to parameters in Stored Procedure

Maybe I'm being an idiot here, but I'm trying to assign a default DateTime value to a Stored Procedure in MS SQL Server 2005 but can't get it to work eg:

CREATE PROCEDURE MyProcedure
(
    @MyInteger    INT = 123,
    @MyDateTime   DATETIME = CONVERT(DATETIME, '1753-01-01 00:00:00', 20)
)
AS
BEGIN ... (snip)

So if the @MyDateTime input parameter isn't specified, it should use '1753-01-01 00:00:00' by default, but I get the error...

Incorrect syntax near the keyword 'CONVERT'.

I can get it to work for Integers just fine. What am I doing wrong?


Edit: from the answers below, I eventually went with the following inside the Sproc itself:

CREATE PROCEDURE MyProcedure
(
    @MyInteger    INT = 123,
    @MyDateTime   DATETIME = NULL
)
AS
BEGIN
    SET NOCOUNT ON

    SET @MyDateTime = COALESCE(@MyDateTime, CONVERT(DATETIME, '1753-01-01 00:00:00', 20))

    ...snip...
END
like image 474
Sunday Ironfoot Avatar asked Jun 20 '11 15:06

Sunday Ironfoot


People also ask

How do I pass a datetime parameter to a stored procedure in SQL?

CREATE PROCEDURE GetData ( @ID INT = NULL , @StartDate DATETIME = NULL , @EndDate DATETIME = NULL ) AS SET NOCOUNT ON; SELECT * FROM TableA A JOIN TableB B ON A. a = B. b WHERE ( @ID IS NULL OR S.ID = @ID ) AND ( @StartDate IS NULL AND @EndDate IS NULL OR DateColumn BETWEEN @StartDate AND @EndDate );

Can a stored procedure have default values for its parameters?

A procedure can have a maximum of 2100 parameters; each assigned a name, data type, and direction. Optionally, parameters can be assigned default values.

Can we assign a default value to out variable used in a procedure?

You can specify a default value for the parameters. Stored procedures can return a value to the calling program if the parameter is specified as OUTPUT. The parameter values must be a constant or a variable. It cannot be a function name.

Which can be used to assign a default value to in parameters?

You can assign a default value for a parameter in the create procedure statement. This value, which can be any constant, is used as the argument to the procedure if the user does not supply one.


2 Answers

@MyDateTime DATETIME ='1753-01-01 00:00:00'

Or right within the sproc you can do this:

SELECT @MyDateTime = (SELECT CONVERT(DATETIME, '1753-01-01 00:00:00', 20))

The error is due to calling CONVERT, which you cannot do when defaulting parameters.

like image 113
JonH Avatar answered Oct 02 '22 18:10

JonH


You can't have the CONVERT() function call in there, just assign the default value using the relevent datetime string.

like image 33
Ben Robinson Avatar answered Oct 02 '22 18:10

Ben Robinson