Difference Between SP and UDF Is Listed Below
Difference Between SP and UDF Is Listed Below
User-Defined Functions
User-Defined Functions (UDFs) in Sql Server. All the examples in this article uses
the pubs database.
There are three Types of UDFS in Sql Server:
1. Scalar
2. Inline Table-Valued
3. Multi-statement Table-Valued
Let us go through each of these with examples:
1. Scalar User-Defined Function
A Scalar UDF can accept 0 to many input parameter and will return a single
value. A Scalar user-defined function returns one of the scalar (int, char,
varchar etc) data types. Text, ntext, image and timestamp data types are not
supported. These are the type of user-defined functions that most developers are
used to in other programming languages.
Note: For Scalar UDFS we need to use Two Part Naming Convention i.e. in the
above two statements we are using dbo.AddTwoNumbers.
Whether Below statement is correct? No, because it is not using two-part naming
convention. Try executing the below statement it will error out
PRINT AddTwoNumbers(10,20)
USE PUBS
GO
CREATE FUNCTION GetAuthorsByState
( @state char(2) )
RETURNS
6
7
@AuthorsByState table (
8
au_id Varchar(11),
9
au_fname Varchar(20)
10
)
11
AS
BEGIN
12
13
INSERT INTO @AuthorsByState
14
SELECT au_id,
15
au_fname
16
FROM Authors
17
WHERE state = @state
18
19
IF @@ROWCOUNT = 0
BEGIN
20
INSERT INTO @AuthorsByState
21
VALUES ('','No Authors Found')
22
END
23
24
RETURN
25
END
GO
26
27
28
We can use the below statements to get all the authors in the given input state:
SELECT * FROM GetAuthorsByState('CA')
SELECT * FROM GetAuthorsByState('XY')