# Create a Scalar-Valued Function

In 
Published 2022-12-03

This tutorial explains to you how to create a SQL Server Scalar-Valued function. This article has a step-by-step approach.

In SQL Server you can create/ define 3 types of User-defined functions:

  • Scalar-valued Function => return a value
  • Inline Table-valued Function => no function body; the table is the result set of a single SELECT statement
  • Multi-statement Table-valued Function => return a table data type

Here are the steps for creating a Scalar-valued Function into a SQL Server Database using the SQL Server Management Studio.

First connect to the Microsoft SQL Server Management Studio.

Right click on "Functions" choose "New" and "Scalar-valued Function". You will see the following tab:

This is a template, and you have to modify it :

When your code is ok, click on "Execute" and the function will be created.

Here is the code, you have to run to test the function:

Here is the T-SQL code for creating this SQL Server function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE FUNCTION MyFunction(
     -- Add the parameters for the function here
     @Param1 varchar(90) = '1'
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @ResultVar int;
 
    -- Add the T-SQL statements to compute the return value here
    SET @ResultVar = (SELECT count(*) from dbo.Table_1 where column1=@Param1);
 
    -- Return the result of the function
    RETURN @ResultVar;
 
END
GO