03 functions

33
FUNCTIONS

Upload: jagan-yalla

Post on 14-Sep-2015

213 views

Category:

Documents


1 download

DESCRIPTION

db2 functions, db2 syntax.

TRANSCRIPT

  • FUNCTIONS

  • 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 FunctionAggregate FunctionTable FunctionRow Function

    FUNCTION DEFINITION

  • 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 of scalar function: 1. Length()2. Substr()3. Ucase() or Upper4. Values 5. To_Char etcUsage examples:select length (empname) from emp;Select * from emp where length (empname) > 9;select to_char(current timestamp,YYYYMMDD) from sysibm.sysdummy1;

    SCALAR FUNCTION EXAMPLES

  • 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;

    AGGREGATE 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.

    TABLE 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.

    ROW 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 RowExternal ScalarExternal tableOLE DB External table

    USER DEFINED FUNCTIONS

  • This can be constructed from a function that has been already registered with a database. Types:Scalar.Columnar.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 user-defined distinct data type to selectively inherit some of the semantics of the built-in data type on which it is base.

    SOURCED FUNCTIONS

  • CREATE FUNCTION [FunctionName] 1( ) 2RETURNS [OutputDataType] 3 4SOURCE [SourceFunction] 5 6FunctionName: 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)

    SYNTAX FOR SOURCED 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.

    SQL FUNCTIONS

  • CREATE FUNCTION [FunctionName] ( ) RETURNS [[OutputDataType] | TABLE ( [ColumnName] [ColumnDataType] ,... ) | ROW ( [ColumnName] [ColumnDataType] ,... )]

    [SQLStatements] | RETURN [ReturnStatement]

    SYNTAX

  • 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

  • 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.

    EXPLANATION CONTD

  • CREATE FUNCTION julian_date(in_date DATE) 1RETURNS CHAR(7) 2LANGUAGE SQL 3RETURN 4RTRIM(CHAR(YEAR(in_date))) || SUBSTR(DIGITS(DAYOFYEAR(in_date)), 8) 5EXAMPLE

  • 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.

    EXTERNAL SCALAR FUNCTION

  • CREATE FUNCTION [FunctionName] ( ) 1RETURNS [OutputDataType] 2 3EXTERNAL 4LANGUAGE [C | JAVA | CLR | OLE] 5PARAMETER STYLE [DB2GENERAL | JAVA | SQL] 6 7 8 9 10 11 12 13 14SYNTAX

  • 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 functionJAVA : DB2 calls the UDF as a method in a Java class.CLR : DB2 calls the UDF as a method in a .NET classOLE : DB2 calls the UDF as if it were a method exposed by an OLE automation object.

    SYNTAX EXPLANATION

  • The 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 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.

    SYNTAX EXPLANATION

  • CREATE FUNCTION center(INT, DOUBLE) RETURNS DOUBLE EXTERNAL NAME '/home/db2inst1/myfuncs/double' LANGUAGE C PARAMETER STYLE SQL DETERMINISTIC NO SQLEXAMPLE

  • CREATE FUNCTION [FunctionName] ( ) RETURNS TABLE ( [ColumnName] [ColumnDataType] ,... ) EXTERNAL LANGUAGE [C | JAVA | CLR | OLE] PARAMETER STYLE [DB2GENERAL | SQL]

    EXTERNAL TABLE FUNCTIONS SYNTAX

  • 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 ACTIONEXAMPLE

  • A function which composed of single SQL statement.It can return a single scalar value.

    Example1:CREATE FUNCTION sqlfunc.this_month()--> 1returns varchar(25)--> 2specific sqlfunc.this_moth()--> 3langague sql--> 4not deterministic--> 5no external action--> 6contains sql--> 7return monthname(current_date)--> 8

    STRUCTURE OF SINGLE STATEMENT SQL FUNCTION

  • CREATE FUNCTION sqlfunc.strip_ltblanks(string varchar(1024))--> 1returns varchar(1024)--> 2specific sqlfunc.strip_ltblanks()--> 3langague sql--> 4not deterministic--> 5no external action--> 6contains sql--> 7return ltrin(rtrim(string))--> 8

    This function has input parameter. This function trims the input string both sides and returns the output.

  • 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'--> 8STRUCTURE OF SINGLE STATEMENT SQL TABLE FUNCTION

  • 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.

    COMPOUND SQL SCALAR FUNCTIONS

  • 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 atomicdeclare 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

  • 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.

    COMPOUND SQL TABLUR FUNCTIONS

  • CREATE FUNCTION sqlfunc.top_salaries()return table (empno char(6),lastname varchar(15),salary deciaml(9,12))specific sqlfunc.top_salarieslangauge sqlnot determinsticno external actionreads sql databegin atomicdeclare 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 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 statementsDECLARE [Variable] DEFAULT [Value]DECLARE [Condition]SET (assignment-statement)Conditional statements : IFLooping statements : FOR, WHILETransfer of control statements : CALL, ITERATE,LEAVE ,RETURNError management statements : SIGNAL

    SQL PROCEDURAL STATEMENTS IN FUNCTIONS

  • CREATE FUNCTION sqlfunc.test(value integer)return integerbegin atomicdeclare counter integer;set counter = 0;loop label;while counter < value doset counter = counter + 5;if counter > value theniterate loop_label;elseif counter > value thenleave loop_label;end if;end while;return counter;end

  • 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 [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.ERROR HANDLING IN FUNCTIONS