Apr 21, 2012

Computed parameters in Stored Procedure


 You are aware of Computed Columns in SQL ServerIn a similar way you can also use Computed Parameters. Consider the following procedure.
1.Create procedure test
2.(
3.@datetime datetime,
4.@date date = @datetime
5.)
6.as
7.select @datetime as date_with_time, @date as date_only
When you execute the procedure you get this result
1.EXEC '2001-10-18 12:45:22.000'
1.date_with_time          date_only
2.----------------------- ----------
3.2001-10-18 12:45:22.000 2001-10-18
As you see the parameter accepts the value supplied for @datetime and convert it to date datatype. 
When you supply value for @date, it will ignore the value of @datetime, the default value for it
1.EXEC '2001-10-18 12:45:22.000','2012-01-22 19:15:12.000'
1.date_with_time          date_only
2.----------------------- ----------
3.2001-10-18 12:45:22.000 2012-01-22
However it is not possible to use an expression for the computed paramters 
ie @date date=dateadd(day,10,@datetime) will not work. You should be aware of this when you use paramers
this way.

No comments:

Post a Comment

Hi,

Thanks for your visit to this blog.
We would be happy with your Queries/Suggestions.