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
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 );
A procedure can have a maximum of 2100 parameters; each assigned a name, data type, and direction. Optionally, parameters can be assigned default values.
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.
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.
@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.
You can't have the CONVERT() function call in there, just assign the default value using the relevent datetime string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With