You are on page 1of 33

FUNCTIONS

FUNCTION DEFINITION

A function is an encapsulated as set of instructions that are


designed to perform a specific task.
It can have one or more inputs parameters (used to customize
action)
It can have one or more output parameters (used to customize
action)
Four type of functions are available in db2 (SYSTEM DEFINED
FUNCTIONS).
Scalar Function
Aggregate Function
Table Function
Row Function

SCALAR FUNCTION
Scalar function are single value return functions.
It can be used to perform a simple tasks.
Scalar functions can be referenced by SQL statements wherever
expressions are supported
Scalar function improves the overall query performance when used in
query predicates since the functions logic executed directly on server.
Can be act as filter, thus limiting the number of rows return to client.
Typically used to perform the mathematical operations.

Limitations:
Can return only one value at a time, multiple values and result sets
cannot be returned.
Transaction management is not supported, so it cannot be commit and
rollback inside the body of scalar functions.

SCALAR FUNCTION
EXAMPLES
Examples of scalar function:
1. Length()
2. Substr()
3. Ucase() or Upper
4. Values
5. To_Char etc
Usage examples:
select length (empname) from emp;
Select * from emp where length (empname) > 9;
select to_char(current timestamp,YYYYMMDD) from
sysibm.sysdummy1;

AGGREGATE FUNCTIONS

Also known as Columnar function.


Returns a scalar value that is the result of an evaluation of
input values.
Typically, a set of input values come from a column within a
table.
Example: Max () and Min() etc.
Usage:

select max(salary) from emp;


select min(age) from emp;

TABLE FUNCTIONS
It returns a table to the SQL statement which reference it.
It can be referenced in from clause only.
Table returned by table function can be used in performing
any operations.
It works like read only view.
It can also make operating system calls, as well as read
data from files and access data from a network.
Limitations:
Similar to scalar functions.

ROW FUNCTIONS
It returns a single row.
Can only be used with user defined structured types.
Typically, row functions are used to map structured type attributes
to a row of built-in data type values in order to make structured
type attributes accessible in queries or SQL operations.

USER DEFINED
FUNCTIONS
UDFs are special objects that can be used to extend the and
enhance the support provided by the built in functions.
Created by database users.
UDFs can use system calls and DB2 administrative APIs.
Types of UDF:
Sourced (or Template)
SQL scalar, table or Row
External Scalar
External table
OLE DB External table

SOURCED FUNCTIONS
This can be constructed from a function that has been already
registered with a database.
Types:
1. Scalar.
2. Columnar.
3. Tabular.
Designed to overload specific operators such as + , -,* and /.
Underlying data types of source function and overloaded function
should be same.
The most common use of sourced functions is to enable a userdefined distinct data type to selectively inherit some of the semantics
of the built-in data type on which it is base.

SYNTAX FOR SOURCED


FUNCTIONS
CREATE FUNCTION [FunctionName]

1
( <<[ParameterName]> [InputDataType] ,...> )
2
RETURNS [OutputDataType]
3
<SPECIFIC [SpecificName]>
4
SOURCE [SourceFunction] <([DataType] ,...)>
5
<AS TEMPLATE>
6
FunctionName: identifies the name to be assigned to the sourced
function that is to be created.
ParameterName: identifies the name to be assigned to one or more
function parameters.
InputDataType: identifies the type of data the function expects to
receive for the parameteridentified by ParameterName.
OutputDataType: identifies the type of data the function is to return.

SYNTAX FOR SOURCED


FUNCTIONS
SpecificName: identifies the specific name to be assigned to the UDF.
This name can be used later to refer to or delete (drop) the function;
however, it cannot be used to invoke the function.
SourceFunction: identifies the name that has been assigned to the
existing function that is to be used to create the sourced function.
DataType: identifies the type of data that the existing function expects to
receive for eachparameter required.

EXAMPLE:
CREATE FUNCTION AVG(YEAR) RETURNS YEAR SOURCE
SYSIBM.AVG(INTEGER)

SQL FUNCTIONS
Its a UDF which constructed using only SQL an
procedure language SQL statements.
Its scalar in nature.
It can return a value or single row or entire table.

SYNTAX
CREATE FUNCTION [FunctionName] ( <<[ParameterName]>
[InputDataType] ,...> )
RETURNS [
[OutputDataType] |
TABLE ( [ColumnName] [ColumnDataType] ,... ) |
ROW ( [ColumnName] [ColumnDataType] ,... )
]
<SPECIFIC [SpecificName]>
<LANGUAGE SQL>
<DETERMINISTIC | NOT DETERMINISTIC>
<EXTERNAL ACTION | NO EXTERNAL ACTION>
<CONTAINS SQL | READS SQL DATA | MODIFIES SQL DATA>
<STATIC DISPATCH>
<CALLED ON NULL INPUT>
[SQLStatements] |
RETURN [ReturnStatement]

EXPLANATION
LANGUAGE SQL : indicates that the function was written using SQL.
DETERMINISTIC | NOT DETERMINISTIC: is used to identify whether the
function always returns the same scalar value, table, or row when it is
called with the same parameter values specified (DETERMINISTIC) or not
(NOT DETERMINISTIC). If neither clause is specified, it is implied that the
function may return different results each time it is called with the same
parameter values specified.
EXTERNAL ACTION | NO EXTERNAL ACTION: identifies whether the
function performs some action that changes the state of an object that
DB2 does not manage (EXTERNAL ACTION) or not (NO EXTERNAL
ACTION). An example of an external action is sending an email message
or writing a record to an external file. If neither clause is specified, it is
implied that the function may perform some type of external action.

EXPLANATION CONTD
CONTAINS SQL | READS SQL DATA | MODIFIES SQL DATA: identifies
which types of SQL statements have been coded in the body of the
UDF. Three different values are available.
CONTAINS SQL : The body of the UDF contains executable SQL
statements that neither read nor modify data.
READS SQL DATA : The body of the UDF contains executable SQL
statements that read but do not modify data.
MODIFIES SQL DATA : The body of the UDF contains executable SQL
statements that can both read and modify data.
STATIC DISPATCH: is used to indicate that at function resolution time,
DB2 is to choose a function based on the static types (declared types)
of the parameters of the function.
CALLED ON NULL INPUT: indicates that the function is to be called
regardless of whether any of its parameters contain null values.

EXAMPLE

CREATE FUNCTION julian_date(in_date DATE)


RETURNS CHAR(7)
LANGUAGE SQL
3
RETURN
4
RTRIM(CHAR(YEAR(in_date))) ||
SUBSTR(DIGITS(DAYOFYEAR(in_date)), 8) 5

1
2

EXTERNAL SCALAR
FUNCTION
Written in High level language such as C, C++ or Java.
Steps:
1. Construct the body of the UDF using high level language.
2. Compile the UDF.
3. Link the UDF.
4. Debug the UDF and repeat step 2 to 4 till all issues resolved.
5. Physically store the library containing the UDF on the server
workstation. Additionally, the system permissions for the library file
containing the UDF must be modified so that all user scan execute it.
6. Register the UDF with a DB2 database using the appropriate form of
the CREATE FUNCTION SQL statement.

SYNTAX
CREATE FUNCTION [FunctionName] ( <<[ParameterName]>
[InputDataType] ,...> ) 1
RETURNS [OutputDataType]
2
<SPECIFIC [SpecificName]>
3
EXTERNAL <NAME [ExternalName] | [Identifier]>
4
LANGUAGE [C | JAVA | CLR | OLE]
5
PARAMETER STYLE [DB2GENERAL | JAVA | SQL] 6
<DETERMINISTIC | NOT DETERMINISTIC>
7
<FENCED | NOT FENCED>
8
<RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT>
<NO SQL | CONTAINS SQL | READS SQL DATA> 10
<STATIC DISPATCH>
11
<EXTERNAL ACTION | NO EXTERNAL ACTION> 12
<SCRATCHPAD <[100 | [SPSize]]> | NO SCRATCHPAD> 13
<DBINFO | NO DBINFO>
14

SYNTAX EXPLANATION
External Name: identifies the name of the library and the name of the function
in the library that contains the executable code of the external function being
registered.
Identifier: identifies the name of the library that contains the executable code
of the external function being registered, but only if the function was written
using C or C++. The DB2Database Manager looks for a function that has the
same name as the library name specified.
SPSize: specifies the amount of memory, in bytes, that is to be set aside and
used as a scratchpad area.
LANGUAGE [C | JAVA | CLR | OLE] clause is used to identify the high-level
programming language convention that the body of the UDF conforms to. Four
different values are available:
C : DB2 calls the UDF as if it were a C function
JAVA : DB2 calls the UDF as a method in a Java class.
CLR : DB2 calls the UDF as a method in a .NET class
OLE : DB2 calls the UDF as if it were a method exposed by an OLE automation
object.

SYNTAX EXPLANATION
The <SCRATCHPAD <[100 | [SPSize]]> | NO SCRATCHPAD> clause is used to
indicate whether memory is to be allocated and set aside as a persistent
storage area for the UDF(SCRATCHPAD) or not (NO SCRATCHPAD). If the
SCRATCHPAD clause is specified, DB2 allocates the appropriate amount of
memory the first time the function is invoked. Once a scratchpad is created
and populated, its contents are preserved from one function invocation to the
next any changes made to the scratchpad by the UDF on one call will be
there on a sub sequent call.
The <DBINFO | NO DBINFO> clause is used to identify whether information
known by DB2is to be passed to the UDF as an additional argument when the
function is invoked (DBINFO)or not (NO DBINFO). If the DBINFO clause is
specified, DB2 passes a data structure containing information like the name of
the currently connected database, the application run-time authorization ID,
the version, release, and modification level of the database server invoking the
function, and the operating system being used by the server to the UDF.

EXAMPLE

CREATE FUNCTION center(INT, DOUBLE) RETURNS


DOUBLE EXTERNAL NAME
'/home/db2inst1/myfuncs/double' LANGUAGE C
PARAMETER STYLE SQL DETERMINISTIC NO SQL

EXTERNAL TABLE
FUNCTIONS SYNTAX
CREATE FUNCTION [FunctionName] ( <<[ParameterName]>
[InputDataType] ,...> )
RETURNS TABLE ( [ColumnName] [ColumnDataType] ,... )
<SPECIFIC [SpecificName]>
EXTERNAL <NAME [ExternalName] |
[Identifier]> LANGUAGE [C | JAVA | CLR | OLE]
PARAMETER STYLE [DB2GENERAL | SQL]
<DETERMINISTIC | NOT DETERMINISTIC>
<FENCED | NOT FENCED>
<RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT>
<NO SQL | CONTAINS SQL | READS SQL DATA>
<STATIC DISPATCH>
<EXTERNAL ACTION | NO EXTERNAL ACTION>
<SCRATCHPAD <[100 | [SPSize]]> | NO SCRATCHPAD>
<DBINFO | NO DBINFO>

EXAMPLE

CREATE FUNCTION empdata (VARCHAR(30),


VARCHAR(255)) RETURNS TABLE (empid INT,
lname CHAR(20), fname CHAR(20))
EXTERNAL NAME
'/home/db2inst1/myfuncs/EMPDATA'
LANGUAGE C PARAMETER STYLE SQL
DETERMINISTIC NOT FENCED NO SQL NO
EXTERNAL ACTION

STRUCTURE OF SINGLE
STATEMENT SQL FUNCTION
A function which composed of single SQL statement.
It can return a single scalar value.
Example1:
CREATE FUNCTION sqlfunc.this_month()
returns varchar(25)
specific sqlfunc.this_moth()
langague sql
not deterministic
no external action
contains sql
return monthname(current_date)

--> 1
--> 2
--> 3
--> 4
--> 5
--> 6
--> 7
--> 8

CREATE FUNCTION sqlfunc.strip_ltblanks(string varchar(1024)) --> 1


returns varchar(1024)
--> 2
specific sqlfunc.strip_ltblanks()
--> 3
langague sql
--> 4
not deterministic
--> 5
no external action
--> 6
contains sql
--> 7
return ltrin(rtrim(string))
--> 8
This function has input parameter. This function trims the input string
both sides and returns the output.

STRUCTURE OF SINGLE
STATEMENT SQL TABLE
FUNCTION
Its a table function which has capability of returning
table as output.
Example:
CREATE FUNCTION sqlfunc.male_Salaries() --> 1
returns table(empno char(6),lastname varchar(15),salary decimal(9,2))
--> 2
specific sqlfunc.male_Salaries()
--> 3
langague sql
--> 4
not deterministic
--> 5
no external action --> 6
reads sql data
--> 7
return select empno,lastname,salary
from employee where sex='M'
--> 8

COMPOUND SQL SCALAR


FUNCTIONS
A special mechanism which allows you to group
multiple SQL statements into a single executable
block.
This reduces amount of over ahead.
This has minimal control flow significant data flow.

CREATE FUNCTION sqlfunc.last_Day_of_month()


returns varchar(24)
specific sqlfunc.last_Day_of_month
language sql
not deterministic
no external action
contains sql
begin atomic
declare date_str varchar(12);
declare month, year INTEGER;
declare date_val DATE;
SET month = month (current_date) + 1;
SET YEAR = YEAR (current_date)
SET DATE_STR = RTRIM(CHAR(YEAR));
SET DATE_STR = CONCAT(DATE_STR, '-');
SET DATE_STR = CONCAT ((DATE_STR, RTRIM(CHAR(MONTH)));
SET DATE_STR = CONCAT ( DATE_STG ) - 1 DAY;
RETURN DAYNAME(date_val);

end

COMPOUND SQL TABLUR


FUNCTIONS
Similar to compound sql scalar function except
return values.
Function has capability of returning a table instead
of single scalar value.
Output table is also known as result set.

CREATE FUNCTION sqlfunc.top_salaries()


return table (empno char(6),lastname varchar(15),salary deciaml(9,12))
specific sqlfunc.top_salaries
langauge sql
not determinstic
no external action
reads sql data
begin atomic
declare avg_salary decimal(9,2);
set avg_salary = decimal((select avg(salary) from employee));
return select empno,lastname,salary from employee where salary >
avg_salary;
end

SQL PROCEDURAL
STATEMENTS IN FUNCTIONS
SQL PL has a simple syntax that includes support for variables,
conditional statements, looping statements, transfer of control
statements, error management statement, result sets manipulation
statements.
Variable related statements
DECLARE [Variable] DEFAULT [Value]
DECLARE [Condition]
SET (assignment-statement)
Conditional statements
: IF
Looping statements : FOR, WHILE
Transfer of control statements
: CALL, ITERATE,LEAVE ,RETURN
Error management statements
: SIGNAL

CREATE FUNCTION sqlfunc.test(value integer)


return integer
begin atomic
declare counter integer;
set counter = 0;
loop label;
while counter < value do
set counter = counter + 5;
if counter > value then
iterate loop_label;
elseif counter > value then
leave loop_label;
end if;
end while;
return counter;
end

ERROR HANDLING IN
FUNCTIONS
Trapping and processing any error and/or warning conditions that may
occur within the scope of the function.
Easiest way to handle the errors using SIGNAL statement.
SIGNAL SYNTAX:
1.SIGNAL [condition_value] = SET MESSAGE_TEXT [ MESSAGE]
2. SIGNAL SQLSTATE <VALUE> [SQLSTATE_VALUE]
= SET MESSAGE_TEXT [ MESSAGE]
Condition_Value = Identifies a condition that was declared earlier within
the compound sql.
SQLSTATE_VALUE =identifies a string constant with exactly 5 characters
that represents an SQLSTATE value.
Message_Text: Up to 70 characters, describes the error or warning
condition occurred.

You might also like