Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I default a sql stored procedure parameter to a dynamic expression?

I want to have a "@myDate" parameter in a stored procedure that defaults to 2 years prior to today if nothing else is specified. I tried doing something like this in my procedure definition:

CREATE PROCEDURE myProcedure(   @param1 int,
                                @param2 varchar(20),
                                @param3 int = null,
                                @myDate datetime = dateadd(year,-2,getDate()) )

I'm getting the following syntax error:

Incorrect syntax near '('.

Does sql server allow you to set dynamic expressions as default parameter values? If not, how can I get around this (other than the clumsy IF @myDate is null SET @myDate=...)?

like image 880
froadie Avatar asked Mar 08 '11 08:03

froadie


People also ask

Can we create dynamic SQL using stored procedures containing parameters?

Using dynamic SQL inside stored proceduresThe dynamic SQL statement is constructed based on the input parameters passed to the stored procedure and is executed by the EXEC command. When we execute the stored procedure with input parameter productid only, the SQL statement is constructed as shown in the below image.

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 use dynamic SQL in stored procedure?

You can use only a DDL COMMENT statement as dynamic SQL in a stored procedure. You cannot specify a DML COMMENT statement to fetch the comments for database objects, columns of a table, and parameters. A CREATE DATABASE or CREATE USER statement used as dynamic SQL in a stored procedure must contain the FROM clause.

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.


2 Answers

You can't use an expression as default value, and there is no really elegant way of doing this.

You can use isnull or coalesce instead of the if statement:

set @myDate = isnull(@myDate, dateadd(year, -2, getdate()))
like image 65
Guffa Avatar answered Nov 11 '22 23:11

Guffa


No.

From the docs:

The default value must be a constant or it can be NULL

like image 38
The Scrum Meister Avatar answered Nov 11 '22 22:11

The Scrum Meister