I already have a function in SQL Server 2005 as:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric) Returns varchar(100) AS Begin <Function Body> End
I want to modify this function to accept addition optional parameter @ToDate. I am going to add logic in function if @Todate Provided then do something else continue with existing code.
I modified the function as:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric,@ToDate DateTime=null) Returns varchar(100) AS Begin <Function Body> End
Now I can call function as:
SELECT dbo.fCalculateEstimateDate(647,GETDATE())
But it gives error on following call:
SELECT dbo.fCalculateEstimateDate(647)
as
An insufficient number of arguments were supplied for the procedure or function dbo.fCalculateEstimateDate.
which as per my understanding should not happen.
Am I missing anything? Thanks in advance.
We can create function with default parameters. To call that function without that parameter, you need to pass NULL to that parameter. Let's say I have function with Two Parameters, in which second parameter can be optional. Let me know if it helps you in any way.
Fortunately, it's pretty easy to make some parameters required and others optional. You simply give them a default value. The first three parameters are required and the next three aren't.
Use SQL Server Management Studio Select on the plus sign next to the database that contains the function you wish to modify. Select on the plus sign next to the Programmability folder. Select the plus sign next to the folder that contains the function you wish to modify: Table-valued Function.
You must own the function to use ALTER FUNCTION . To change a function's schema, you must also have CREATE privilege on the new schema. To alter the owner, you must also be a direct or indirect member of the new owning role, and that role must have CREATE privilege on the function's schema.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric) Returns varchar(100) AS Declare @Result varchar(100) SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT) Return @Result Begin End CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null) Returns varchar(100) AS Begin <Function Body> End
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