Working with functions

6.3 Working with functions

An SQL function is a method or a command that takes in zero or more input parameters and returns a single value. All databases have a few standard pre-defined functions for mathematical operations, string manipulations and a few other database specific methods.

A user can also create custom defined functions, also known as user-defined functions, to fulfill any requirements that are not served by the default functions library.

6.3.1 Types of functions

Functions can be classified into the following types based on their behavior and input data set they operate on:

 Scalar - Aggregate - String

 Table In addition to this classification you can have built-in functions, that is, functions supplied

with the database software, and User-defined functions (UDFs), that is, custom functions created by users. A UDF is an extension to the SQL language. It is a small program that you write, similar to a host language subprogram or function. However, a user-defined function is often the better choice for an SQL application because you can invoke it in an SQL statement. In DB2, you can create scalar or table UDFs using SQL PL, PL/SQL, C/C++, Java, CLR (Common Language Runtime), and OLE (Object Linking and Embedding).

6.3.1.1 Scalar functions

A scalar function is a function that, for each set of one or more scalar parameters, returns a single scalar value. Scalar functions are commonly used to manipulate strings or perform basic mathematical operations within SQL statements. Scalar functions cannot include SQL statements that will change the database state; that is, INSERT, UPDATE, and DELETE statements are not allowed.

For example, the LENGTH built-in function returns the length of a string as shown below:

SELECT length('Mary') FROM sysibm.sysdummy1

The above SQL statement executed while connected to a DB2 database returns the value of 4 which is the length of the string 'Mary'.

Scalar functions can be referenced anywhere that an expression is valid within an SQL statement, such as in a select-list, or in a FROM clause. For example:

SELECT EMPNO, LASTNAME, YEAR(CURRENT DATE - BRTHDATE) FROM EMPLOYEE WHERE WORKDEPT = 'D01'

Database Fundamentals 154 The above example shows the YEAR function which is used to retrieve the year from the

output of "CURRENT DATE - BRTHDATE". Built-in scalar functions perform well because their logic is executed on the database

server as part of the SQL statement that references it. When used in predicates, scalar function usage can improve overall query performance. When a scalar function is applied to a set of candidate rows, it can act as a filter, limiting the number of rows that must be returned to the client.

6.3.1.1.1 Aggregate functions

An aggregate function is a function that, for each set of one or more scalar parameters, returns a single scalar value. For example, AVG(COL_NAME) returns the average value of column ’COL_NAME’.

6.3.1.1.2 String functions

A string function is a function that accepts at least one or more scalar string parameters and zero or more scalar integer parameters of a single scalar value (of type string or integer). For example, SUBSTR('abcdefghi',3,4) takes three parameters (source string, substring start location, and number of characters from start location) and returns the appropriate substring. In this example, the output would be 'cdef'

6.3.1.2 Table functions

Table functions return a table of rows. You can call them in the FROM clause of a query. Table functions, as opposed to scalar functions, can change the database state; therefore, INSERT, UPDATE, and DELETE statements are allowed. Some built-in table functions in DB2 are SNAPSHOT_DYN_SQL( ) and MQREADALL( ). Table functions are similar to views, but since they allow for data modification statements (INSERT, UPDATE, and DELETE) they are more powerful.

Below is an example of a table function that enumerates a set of department employees:

CREATE FUNCTION getEnumEmployee(p_dept VARCHAR(3)) RETURNS TABLE

(empno CHAR(6), lastname VARCHAR(15), firstnme VARCHAR(12))

SPECIFIC getEnumEmployee RETURN

SELECT e.empno, e.lastname, e.firstnme FROM employee e WHERE e.workdept=p_dept

6.3.2 Creating a function

Similarly to a stored procedure, you can use IBM Data Studio to create a user-defined function, the only difference is that you need to right-click on the user-defined functions folder instead of the Stored procedures folder. Then follow similar steps described earlier for procedures.

Chapter 6 – Stored procedures and functions 155 The CREATE FUNCTION statement is used to register or define a user-defined function or

a function template at the current database server. The listing below provides a simplified syntax of this statement:

>>-CREATE--+------------+--FUNCTION--function-name--------------> '-OR REPLACE-'

.-IN------. >--(--+---------+--parameter-name--| data-type1 |--+-------------+--|-)-->

| | '-| default-clause |-' +-OUT-----+ '-INOUT---'

>-- RETURNS--+-| data-type2 |-------------+--| option-list |-----> '-+-ROW---+--| column-list |-' '-TABLE-'

>--| SQL-function-body |---------------------------------------><

For example, the following SQL PL function reverses a string: CREATE FUNCTION REVERSE(INSTR VARCHAR(40))

RETURNS VARCHAR(40) DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL BEGIN ATOMIC

DECLARE REVSTR, RESTSTR VARCHAR(40) DEFAULT ''; DECLARE LEN INT; IF INSTR IS NULL THEN

RETURN NULL; END IF; SET (RESTSTR, LEN) = (INSTR, LENGTH(INSTR)); WHILE LEN > 0 DO

SET (REVSTR, RESTSTR, LEN) = (SUBSTR(RESTSTR, 1, 1) CONCAT REVSTR, SUBSTR(RESTSTR, 2, LEN - 1), LEN - 1);

END WHILE; RETURN REVSTR;

END @

For comprehensive information on the CREATE FUNCTION syntax and available options, refer to the DB2 v9.7 Information Center .

6.3.3 Invoking a function

Functions can be invoked within any SQL statement or within any data manipulation operation. Functions can not be called explicitly using the ‘CALL’ statement. Typically

Database Fundamentals 156 functions are invoked in a SELECT or VALUES statement. For example, the function

REVERSE defined earlier can be invoked as follows: SELECT reverse(col_name) from myschema.mytable

OR

VALUES reverse('abcd')

In the case of a TABLE function, the function has to be invoked in the FROM clause of an SQL statement since it returns a table. The special TABLE() function must be applied and an alias must be provide after its invocation. For example, to invoke the getEnumEmployee table function created in an earlier section, try the SELECT statement shown in Figure 6.1 below.

Figure 6.1 – Invoking a table function.

6.3.4 Altering and dropping a function

There are two ways to alter any existing user-defined function:

1. Drop the existing function and recreate the function again with a new definition.

2. Use the ‘CREATE OR REPLACE FUNCTION’ syntax instead of ‘CREATE FUNCTION’.

There is also an ALTER FUNCTION statement, but it can only be used to alter specific properties of the function rather than the code itself.

To drop a function use the fully qualified name of the function with the ‘DROP FUNCTION’ statement as shown in example below:

DROP FUNCTION myschema.reverse To alter a function it is preferred to use the CREATE OR REPLACE FUNCTION syntax in

the first place rather than dropping and recreating the function. This is because dropping a function may have other consequences like invalidating objects depending on the function. With the CREATE OR REPLACE FUNCTION syntax this invalidation does not occur.

Chapter 6 – Stored procedures and functions 157