22BI Creating SQL Functions Greg Cannella
Functions let you transform data from the way it is stored in the database to the way you want to use or see it.
Agenda Why functions? Examples Create function Drop function How to see and manage existing functions Handling NULL
Why functions? Fix the sins of your predecessors! Make SQL do new things Use complex routines Helps to keep SQL simple Simplify routine tasks
Examples Convert date from DB format to user format Select datemdy(dbdate) from xyzfile This example converts from 1151021 to 10/21/15
Examples Pricing Routines 1000s of lines of existing code Select price(customer,item,date) from xyzlist Create a stub service program that simply calls your existing code
Examples Create a hyper link <a href="https://google.com">Google</a> Select link(url,urltext) from websitelst -OR- select CONCAT(concat(Concat('<a href="',TRIM(url)), concat('">',TRIM(urltext))), '</a>') from websitelst
Built in Functions List of DB2 functions (just the common ones) Count, Min, Max, Sum, Char, CurDate, CurTime, Hex, Left, Length, Coalesce Substr, Day, Date, Lower, Upper, Right, Round, RRN, Trim Complete list of built in functions: http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc h2func.htm
Create Function Statement CRTSRVPGM SRVPGM(QGPL/DATEMDY) EXPORT(*ALL) Then STRSQL and run the following SQL command. create function LIBRARY.DATEMDY (cyymmdd numeric(7,0) default 0) returns char(8) language rpgle deterministic no sql external name ‘QGPL/DATEMDY(DATEMDY)' parameter style general
Unpacking the create function Parameters In this example: (cyymmdd numeric(7,0)) A single parm is passed into the function For multiple parms the syntax is: (dbname char(128), Parm2 char(10), Parm3 numeric(7,0)) Parameters go into the function but don’t come back.
Unpacking the create function Returns This needs to match the value coming back from the service program. This needs to match exactly. Also note that SQL data types can differ from RPG data types. If the type doesn’t match exactly, you will get a function not found error when trying to use the function.
Unpacking the create function Language You can use any language available on the platform to create functions These can have embedded SQL or not.
Unpacking the create function Deterministic Use ‘not deterministic’ if the same parameters might return different results. Example: The function returns the number of jobs waiting to run in a JOBQ. Use ‘deterministic’ if the function will always return the same value for the same values Example: The function accepts in a date and returns the day of the week.
Unpacking the create function SQL – Probably the most important. This needs to match how your function works. READS SQL DATA – Prevents the underlying function from modifying data in the database CONTAINS SQL – Allows a very limited set of “non-executable” SQL statements. NO SQL – The underlying function can’t run any SQL. MODIFIES SQL DATA – The underlying function can run SQL statements that updates, inserts, deletes, or reads data.
Unpacking the create function External name This is the name of the service program and module Syntax: library/Servicepgm(Module) Example: gregc/datemdy(datemdy)
Unpacking the create function Parameter style I just use ‘parameter style general’ These cause the parameters to function very much like RPGLE service programs. There is also SQL, DB2GENERAL, JAVA, DB2SQL.
Recap create function create function LIBRARY.DATEMDY (cyymmdd numeric(7,0) default 0) returns char(8) language rpgle deterministic no sql external name ‘QGPL/DATEMDY(DATEMDY)' parameter style general
Drop Function drop function library.datemdy
Managing Functions Navigator for I Navigate to the schema where your functions are stored Click on functions
Navigator for i Select a function Actions Definition This will allow you to see and modify everything about the function definition.
Handling Errors and NULL Check your parms upon entry Monitor for bad data Select a default value if failure Datemdy(coalesce(field1,0))
Function Not Found Error Check the library Check the spelling Check that the parameters match (Functions allow overloading.) 7.1 Doesn’t cast variables as well as 7.2. You may need to force type your parameters.
Recap Use functions to transform data Create function Drop function Navigator for managing functions
Thank you Questions?
For more info on functions Create functions http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc fsc.htm Built in functions http://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/db2/rbafzc h2func.htm
Sample Convert Date Program ctl-opt option(*srcstmt:*nodebugio) Debug nomain alwnull(*usrctl) ; // Compile Options: * // Create this as a module. * // CRTSRVPGM SRVPGM(MAGID/DATEMDY) EXPORT(*ALL) * // Then start SQL and run the following SQL command. * // create function magid.DATEMDY * // (cyymmdd numeric(7,0) default 0) * // returns char(8) * // language rpgle * // deterministic * // no sql * // external name 'MAGID/DATEMDY(DATEMDY)' * // parameter style general * //--Entry Prototype dcl-pr DATEMDY char(8); DateIn zoned(7:0) OPTIONS(*NOPASS); end-pr; dcl-proc DATEMDY export ; dcl-pi DATEMDY char(8); end-pi; dcl-s WorkDate date(*iso); dcl-s DateOut char(8); //-- Convert date from CYYMMDD to MM/DD/YY c Eval DateOut = *blanks c Monitor c *cymd Move DateIn WorkDate c *mdy Move WorkDate DateOut c On-error c Endmon return DateOut; end-proc;
Don’t Forget Your Session Surveys Sign in to the Online Session Guide (www.common.org/sessions) Go to your personal schedule Click on the session that you attended Click on the Feedback Survey button located above the abstract Completing session surveys helps us plan future programming and provides feedback used in speaker awards. Thank you for your participation.