开发者

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

开发者 https://www.devze.com 2023-02-15 06:16 出处:网络
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:

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()) )
开发者_如何学C

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=...)?


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()))


No.

From the docs:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消