Advanced Data Base
Advanced Data Base
in SQL Server
User-defined
functions
User-defined functions
Purpose: Encapsulate processing logic prescribed by the user;
Table-valued functions
o Return a set of records which emulate a virtual table
o Depending on function definition:
Inline functions: return a table as a result of a single SQL
statement without requiring explicit definition of that
table;
Multi-statement functions: require explicit definition of
the resulting table.
Scalar-valued functions
Return a single value
Accept multiple parameters
Consist of 2 parts:
o Function header Specifies function name, parameter list
and the data type of the result;
o Function body Defines the internal logic responsible for
producing the result; it ends with the RETURN command
which provides the value or the expression representing
the result.
Scalar-valued functions
Creation:
CREATE FUNCTION function_name ([@parameter_1 AS data_type],
. . . [@parameter_n AS data_type])
RETURNS data_type
AS
BEGIN
SQL commands
RETURN value/expression_to_return
END
Alteration:
Removal:
DROP FUNCTION ...
Table-valued functions
B. MULTI-STATEMENT functions:
return a table as a result
may encapsulate complex processing logic
the structure of the resulting table must be explicitly
defined
Table-valued functions
B. MULTI-STATEMENT functions The syntax:
CREATE FUNCTION function_name ([@parameter_1 AS date_type],
. . . [@parameter_n AS data_type])
AS
BEGIN
SQL statements / commands
RETURN
END
Table variables
Allocate memory space to store record sets defined
as virtual tables.
Allow temporary storage of data organized in
multiple predefined fields so that it can be used for
various processing operations.
Enable efficient data processing if subjected to
relational algebra operators.
May by subjected to SELECT queries & support JOIN
operator relative to other tables.
May be used in INSERT, UPDATE or DELETE statements.
Table variables
Declare @TABLE_VARIABLE_NAME TABLE
(
Field_Name1 Data_Type_1,
Field_Name2 Data_Type_2,
Field_NameN Data_Type_N,
)