Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Optional Input Arguments for functions in T-SQL ?

Status
Not open for further replies.

pradipto

Programmer
Apr 29, 2002
22
US
Hi,

I am a relatively new bee in T-SQL. Suppose I want to write a function that usually takes 2 parameters where the user who uses it has the option of giving say 1 parameter. So I tried to give a default value as following:

-------
Create Function dbo.MyFunction(@Var1 smalldatetime, @Var2 smalldatetime = null)
Returns smalldatetime
As Begin
Declare @Var3 smalldatetime

If @Var2 is null
<do some operation here to calculate @Var3>
Else
<do some other operation here to calculate @Var3>
...
...
Return (@Var3)
-------

Now, this function works fine when I call it as

Select dbo.MyFunction('2004-01-01',null)

but if I try and call it as

Select dbo.MyFunction('2004-01-01')

then it does NOT work and gives me an error:

Server: Msg 313, Level 16, State 3, Line 1
An insufficient number of arguments were supplied for the procedure or function dbo.MyFunction.

How can I make the function take an optional number of arguments?

Thanks

 
Unfortunately, optional values in functions don't work that way. You cannot omit them; specify default keyword instead:
Code:
select dbo.myFunction( '2004-01-01', default )
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top