SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP


How to use Optional Parameters in T-SQL User Defined Functions


If as a t-sql developer or a SQL Server database administrator in your company you work a lot with sql user defined functions, you might probably require optional parameters in udf's.
Optional parameters are widely used in programming as well as in stored procedures in T-SQL.
But optional declaration and logic is a little bit different when user defined function is the topic.

The trick that enables a work around for declaring optional parameters for t-sql functions is checking the parameter with ISNULL() within the sql function definition and calling the function with NULL values where you want to use default value for the optional parameter.
When optional parameter value is passed as NULL then ISNULL() will replace the parameter value with default value of the parameter.





Here is the sample t-sql udf function which uses optional parameter.

CREATE FUNCTION OptionalParameters(
  @i int,
  @optional_Parameter int
) RETURNS int
BEGIN
  -- may be omitted if you use directly the default values
  DECLARE @Default_Value int
  SET @Default_Value = 0

  RETURN @i + ISNULL(@optional_Parameter, @Default_Value)
  -- OR use default value directly as
  --RETURN @i + ISNULL(@optional_Parameter, 0)
END
GO

SELECT
  dbo.OptionalParameters(1, 2),
  dbo.OptionalParameters(1, null)
Code

And above sample sql select statement shows the usage of optional parameter in user defined t-sql function.



SQL Server

SQL Server 2019 Installation
download SQL Server 2019
download SQL Server 2017
download SQL Server 2016
download SQL Server 2014
download SQL Server 2012
MacOS ve SQL Server 2019


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.