Download presentation
Presentation is loading. Please wait.
1
SQL – Procedures And Functions
Copyright 1992, 1993 BY DMC CONSULTING, INC. ALL RIGHTS RESERVED 5650 West Central Avenue, Suite B, Toledo, OH 43615 AS/400 is a trademark of International Business Machines Corporation
2
Stored Procedures
3
Stored Procedures SQL: Written in SQL SQL Proc
External: Written in HL Languages such as RPGLE
4
Stored Procedures CREATE PROCEDURE proc-name Parameters…
IN - INPUT PARAMETERS OUT - OUTPUT PARAMETERS INOUT - INPUT/OUTPUT PARAMETERS CREATE PROCEDURE TESTPROC (IN EMPNO DECIMAL(5,0),OUT EMPNAM CHAR(30))…
5
Stored Procedures Internal Syntax: CREATE PROCEDURE TESTPROC
(IN EMPNO DECIMAL(5,0),OUT EMPNAM CHAR(30))… External Syntax: (IN DECIMAL(5,0),OUT CHAR(30))…
6
Stored Procedures Overloading:
Its possible to create multiple versions of the same procedure, each with a different number of parameters passed: CREATE PROCEDURE TESTPROC (IN EMPNO DECIMAL(5,0))… (IN EMPNO INTEGER,OUT EMPNAM CHAR(30))… In this case, the system generates a unique specific name for each version of the procedure. This is discussed more later.
7
SQL Create Statement Data Types
CHAR – Up to 32,767 bytes of alphanumeric data ( if Null capable) DECIMAL – Up to 63 digits of packed numeric data NUMERIC – Up to 63 digits of zoned numeric data. DATE – Date Data type using a 4 digit year TIME – Time data type in 24 hr format TIMESTAMP - Timestamp data type include date, time, and microseconds (6 digits) INTEGER (INT) – Large Integer (4 Bytes) SMALLINT – A small integer (2 Bytes) BIGINT – A big integer (8 Bytes) FLOAT – Floating Point data type (8 Byte) VARCHAR - Up to 32,740 bytes of character data ( if Null capable) LONG VARCHAR – Variable Length Character Data up to the length of the row BINARY – Up to 32,767 bytes of binary data (32,765 if Null Capable) Note: Decimal is Packed data. Numeric is Zoned data.
8
SQL Create Statement Data Types
VARBINARY - Up to 32,740 bytes of binary data ( if Null capable) GRAPHIC – Up to 16,383 double byte characters (16,382 if Null capable) VARGRAPHIC – Up to double byte characters (16,369 if Null capable) LONG VARGRAPHIC – A string of double byte characters up to the length of the row DOUBLE – Double precision floating point (8 Byte) REAL – Single Precision Floating point (4 Byte) BLOB – Variable length binary string up to 2 gigabytes in length CLOB – Variable length string of characters up to 1 gigabyte in length DATALINK – A string up to 32,718 bytes containing a URL (32,717 if Null capable) DBCLOB – Variable length double byte character string up to 1 gigabyte in length User-Defined (UDT) – Custom functions built with the CREATE FUNCTION statement ROWID - System generated key that uniquely defines a row (40 Bytes)
9
Stored Procedures create procedure your-lib/getcust (in cust char(10))
SQL Procedures create procedure your-lib/getcust (in cust char(10)) language sql dynamic result sets 1 begin declare stmt char(50); declare c1 cursor for s1; set stmt = 'SELECT * FROM your-lib/CUST WHERE CNUMBER = ‘ CONCAT Cust; prepare s1 from stmt; open c1; return; end
10
Stored Procedures call kpflib.getcust ('1’);
11
Stored Procedures create procedure GETCUST (in Custid char(10),
out Oname char(50), out Oaddr1 char(50), out Oaddr2 char(50), out Ocity char(50), out Ostate char(2), out Ozip char(10)) language sql begin SELECT cname,caddr1,caddr2,ccity,cstate,czip into Oname,oaddr1,oaddr2,ocity,ostate,ozip from CUST where cnumber = dec(Custid); return; end
12
Stored Procedures call kpflib.getcust ('1', ' ',' ',' ',' ',' ',' ');
13
Stored Procedures CREATE PROCEDURE proc-name parameters LANGUAGE SQL
Create Procedure Options CREATE PROCEDURE proc-name parameters LANGUAGE SQL options RESULT SETS – Number of result sets returned LANGUAGE – C, SQL, RPG, etc… SPECIFIC – Unique name in case of overloading FENCED – Function should run in a separate thread from the main job. NOT FENCED – Can run in the same thread
14
Stored Procedures CREATE PROCEDURE proc-name parameters LANGUAGE SQL
Create Procedure Options CREATE PROCEDURE proc-name parameters LANGUAGE SQL options NOT DETERMINISTIC – Return value can be unique on every call DETERMINISTIC – Always returns the same results with the same inputs MODIFIES SQL DATA – The Procedure will use SQL to update data in a table READS SQL DATA – The Procedure will use SQL to read data CONTAINS SQL – Some SQL Code is included CALLED ON NULL INPUT – If inputs are null, should the call execute?
15
SQL Create Function Statement
DETERMINISTIC UPPER(‘a’) = ‘A’ date('09/01/2007') = 09/01/07 NOT DETERMINISTIC ORDSTAT(100101) = ‘*’ Now() =
16
Stored Procedures Additional commands for Stored Procedures: BEGIN
CALL CASE END FOR GET GOTO IF ITERATE LEAVE LOOP REPEAT RESIGNAL RETURN SIGNAL WHILE
17
Stored Procedures Special Registers – (Predefined Fields) CURRENT DATE
CURRENT DEGREE CURRENT TIME CURRENT TIMEZONE CURRENT TIMESTAMP CURRENT SCHEMA CURRENT SERVER USER CURRENT PATH SESSION_USER SYSTEM_USER
18
Stored Procedures CREATE PROCEDURE UPDATE_SALARY_2
Sample Stored Procedures CREATE PROCEDURE UPDATE_SALARY_2 (IN EMPLOYEE_NUMBER CHAR(6), IN RATING INT) LANGUAGE SQL MODIFIES SQL DATA CASE RATING WHEN 1 THEN UPDATE CORPDATA.EMPLOYEE SET SALARY = SALARY * 1.10, BONUS = 1000 WHERE EMPNO = EMPLOYEE_NUMBER; WHEN 2 THEN UPDATE CORPDATA.EMPLOYEE SET SALARY = SALARY * 1.05, BONUS = 500 ELSE UPDATE CORPDATA.EMPLOYEE SET SALARY = SALARY * 1.03, BONUS = 0 END CASE
19
Stored Procedures CREATE PROCEDURE RETURN_DEPT_SALARY 1 of 2
Sample Stored Procedures CREATE PROCEDURE RETURN_DEPT_SALARY of 2 (IN DEPT_NUMBER CHAR(3), OUT DEPT_SALARY DECIMAL(15,2), OUT DEPT_BONUS_CNT INT) LANGUAGE SQL READS SQL DATA P1: BEGIN DECLARE EMPLOYEE_SALARY DECIMAL(9,2); DECLARE EMPLOYEE_BONUS DECIMAL(9,2); DECLARE TOTAL_SALARY DECIMAL(15,2)DEFAULT 0; DECLARE BONUS_CNT INT DEFAULT 0; DECLARE END_TABLE INT DEFAULT 0; DECLARE C1 CURSOR FOR SELECT SALARY, BONUS FROM CORPDATA.EMPLOYEE WHERE WORKDEPT = DEPT_NUMBER;
20
Stored Procedures DECLARE CONTINUE HANDLER FOR NOT FOUND 2 of 2
Sample Stored Procedures DECLARE CONTINUE HANDLER FOR NOT FOUND of 2 SET END_TABLE = 1; DECLARE EXIT HANDLER FOR SQLEXCEPTION SET DEPT_SALARY = NULL; OPEN C1; FETCH C1 INTO EMPLOYEE_SALARY, EMPLOYEE_BONUS; WHILE END_TABLE = 0 DO SET TOTAL_SALARY = TOTAL_SALARY + EMPLOYEE_SALARY + EMPLOYEE_BONUS; IF EMPLOYEE_BONUS > 0 THEN SET BONUS_CNT = BONUS_CNT + 1; END IF; END WHILE; CLOSE C1; SET DEPT_SALARY = TOTAL_SALARY; SET DEPT_BONUS_CNT = BONUS_CNT; END P1
21
Stored Procedures CREATE PROCEDURE CREATE_BONUS_TABLE 1 of 2
Sample Stored Procedures CREATE PROCEDURE CREATE_BONUS_TABLE of 2 (IN DEPT_NUMBER CHAR(3), INOUT CNT INT) LANGUAGE SQL MODIFIES SQL DATA CS1: BEGIN ATOMIC DECLARE NAME VARCHAR(30) DEFAULT NULL; DECLARE CONTINUE HANDLER FOR SQLSTATE ’42710’ SELECT COUNT(*) INTO CNT FROM DATALIB.EMPLOYEE_BONUS; DECLARE CONTINUE HANDLER FOR SQLSTATE ’23505’ SET CNT = CNT - 1; DECLARE UNDO HANDLER FOR SQLEXCEPTION SET CNT = NULL; IF DEPT_NUMBER IS NOT NULL THEN CREATE TABLE DATALIB.EMPLOYEE_BONUS (FULLNAME VARCHAR(30), BONUS DECIMAL(10,2), PRIMARY KEY (FULLNAME));
22
Stored Procedures FOR_1:FOR V1 AS C1 CURSOR FOR 2 of 2
Sample Stored Procedures FOR_1:FOR V1 AS C1 CURSOR FOR of 2 SELECT FIRSTNME, MIDINIT, LASTNAME, BONUS FROM CORPDATA.EMPLOYEE WHERE WORKDEPT = CREATE_BONUS_TABLE.DEPT_NUMBER DO IF BONUS > 0 THEN SET NAME = FIRSTNME CONCAT ’ ’ CONCAT MIDINIT CONCAT ’ ’CONCAT LASTNAME; INSERT INTO DATALIB.EMPLOYEE_BONUS VALUES(CS1.NAME, FOR_1.BONUS); SET CNT = CNT + 1; END IF; END FOR FOR_1; END CS1
23
Stored Procedures External Procedures FMYCUSTS IF E K DISK 1 of 2
D InCust S D Custs DS OCCURS(40) D Cname D X S U 0 inz(1) ******************************************************** * Mainline Module C InCust SETLL MYCUSTS C DOU %EOF(MYCUSTS) C InCust READ MYCUSTS C IF %EOF(MYCUSTS) OR C (X = 40) C LEAVE C ENDIF C EVAL X = X + 1 C X OCCUR Custs C ENDDO
24
Stored Procedures External Procedures
C EVAL X = X of 2 C/EXEC SQL C SET RESULT SETS ARRAY :Custs FOR :X Rows C/END-EXEC C MOVE *ON *INLR C RETURN C *ENTRY PLIST C PARM InCUst CREATE PROCEDURE your-lib/GETCUSTS (INOUT Parm1 DECIMAL (6,0 )) RESULT SETS 1 LANGUAGE RPGLE NOT DETERMINISTIC CONTAINS SQL EXTERNAL NAME GETCUSTS PARAMETER STYLE GENERAL
25
Functions
26
Functions CREATE FUNCTION ONCRHLD(CustIn VarChar(5)) RETURNS CHAR(1)
Sample SQL Function CREATE FUNCTION ONCRHLD(CustIn VarChar(5)) RETURNS CHAR(1) LANGUAGE SQL NOT DETERMINISTIC BEGIN Declare YN Char(1); Set YN = 'N'; Select ONHOLD INTO YN from CUSTMAST WHERE CUST = CustIn; RETURN YN; END This function can be used in other SQL statements SELECT ORDER,CUSTNO FROM ORDHDR WHERE ONCRHLD(CUSTNO) = ‘Y’
27
Functions CREATE FUNCTION UnSchedOrders ()
Sample Table Function to Return Orders that do not have a ship date yet. The RPG module, and RPG service program are created using commands such as though shown here: CREATE FUNCTION UnSchedOrders () RETURNS TABLE (Order CHAR(10)) LANGUAGE SQL READS SQL DATA NO EXTERNAL ACTION NOT DETERMINISTIC DISALLOW PARALLEL RETURN SELECT ORDER FROM ORDHDR WHERE OSHPDAT = NULL This function can be used in other SQL statements where tables would normally be seen. SELECT * FROM ORDDTL WHERE ORDER IN(UnSchedOrders)
28
SQL Functions with RPGLE
Sub-Procedure RPG Module Service Program Create Function Statement SQL Function INSTRUCTOR NOTES This will be a quick review of this tool. It will not be covered in depth.
29
SQL Functions with RPGLE
Sample Function to Return Customer Name of 2 H NOMAIN OPTION(*SRCSTMT) FCUST IF E K DISK * Prototype for GetCName(Cust,Part) D GetCName PR D Parm ****************************************************** * GetCName - Takes in a 6 digit customer number * and returns a 30 byte customer name. P GetCName B EXPORT D GetCName PI D CustIn * Define the key list for the contract file. C CUSKEY KLIST C KFLD CUST
30
SQL Functions with RPGLE
2 of 2 * Trap for any error that occurs C MONITOR * Chain to the Contract file C EVAL CUST = CustIn C ConKey CHAIN Cust C IF %FOUND C RETURN CName C ELSE C RETURN *BLANKS C ENDIF * If any error occurs return a zero value C ON-ERROR *PROGRAM C * C ENDMON P E
31
Functions CRTRPGMOD MODULE(SQLFUNCS) DBGVIEW(*SOURCE)
Sample Function to Return Customer Name CRTRPGMOD MODULE(SQLFUNCS) DBGVIEW(*SOURCE) CRTSRVPGM SRVPGM(SQLFUNCS) EXPORT(*ALL) Once created, the sub procedure can be registered with the SQL engine using the SQL command shown below: CREATE FUNCTION your-schema/GETCName (IN DECIMAL(6 0)) RETURNS CHAR(30) EXTERNAL NAME 'your-schema/SQLFUNCS(GETCNAME)' LANGUAGE RPGLE PARAMETER STYLE GENERAL
32
SQL Functions with RPGLE
Sample Function to Convert a Date of 3 H NOMAIN ********************************************************* * SQLFUNCS - This module is used to create the Service * * program SQLFUNCS, which includes the * * following exports: * * * * CvtDate - Converts CYYDDD into *USA DATE (MM/DD/YYYY)* * Prototype for CvtDate(DATEIN) D CvtDate PR D D Parm VARYING
33
SQL Functions with RPGLE
2 of 3 ********************************************************* * CvtDate - Takes in a 6 byte parameter and translates * * it to a date and returns that date * * * P CvtDate B EXPORT D CvtDate PI D D DateIn VARYING D DateWork DS D LongJul D WrkCent D CentCd D WrkYr D WrkDys D DateFld S D
34
SQL Functions with RPGLE
3 of 3 * Right justify CYYDDD in 7 digit number C EVALR DateWork = DateIn * Change the 1 digit code to a 2 digit number C IF CentCd = 0 C Z-ADD WrkCent C ELSE C Z-ADD WrkCent C ENDIF * Convert the long Julian number into a date field C *LONGJUL MOVE LongJul DateFld * Return the date C RETURN DateFld P E
35
Functions CREATE FUNCTION your-schema/CvtDate (IN VARCHAR(6))
Sample Function to Convert a Date CRTRPGMOD MODULE(SQLFUNCS) DBGVIEW(*SOURCE) CRTSRVPGM SRVPGM(SQLFUNCS) EXPORT(*ALL) Once created, the sub procedure can be registered with the SQL engine using the SQL command shown below: CREATE FUNCTION your-schema/CvtDate (IN VARCHAR(6)) RETURNS DATE EXTERNAL NAME 'your-schema/SQLFUNCS(CvtDate)' LANGUAGE RPGLE PARAMETER STYLE GENERAL
36
SQL Functions with RPGLE
Sample Function to Return a Running Total of 4 * Prototype for RunSum(QTY) D RunSum PR D Parm F D QtyOut F D InNull I 0 D OutNull I 0 D SqlState D FuncName A VARYING D SpecName A VARYING D MesgText A VARYING D Scratch F D Flag I 0
37
SQL Functions with RPGLE
Sample Function to Return a Running Total of 4 ********************************************************* * RunSum - Takes in a floating point value and adds it * * to the previous value * P RunSum B EXPORT D RunSum PI D QtyIn F D QtyOut F D InNull I 0 D OutNull I 0 D SqlState D FuncName A VARYING D SpecName A VARYING D MesgText A VARYING D Scratch F D Flag I 0
38
SQL Functions with RPGLE
Sample Function to Return a Running Total of 4 * Trap for any error that occurs C MONITOR * If this is the first time it’s called * for this select, set the balance to 0 C IF FLAG = -1 C Clear Scratch C ENDIF * Add the input quantity to the scratch quantity C ADD QtyIn Scratch C Z-ADD Scratch QtyOut
39
SQL Functions with RPGLE
4 of 4 * Return the quantity C RETURN * If any error occurs return a zero C ON-ERROR *PROGRAM C C EVAL QtyOut = 0 * C ENDMON P E
40
Functions CRTRPGMOD MODULE(SQLFUNCS) DBGVIEW(*SOURCE)
Sample Function to Calculate a Running Total CRTRPGMOD MODULE(SQLFUNCS) DBGVIEW(*SOURCE) CRTSRVPGM SRVPGM(SQLFUNCS) EXPORT(*ALL) CREATE FUNCTION your-schema/RunSum (INOUT DOUBLE) RETURNS DOUBLE EXTERNAL NAME 'your-schema/SQLFUNCS(RunSum)' LANGUAGE RPGLE PARAMETER STYLE DB2SQL NOT DETERMINISTIC SCRATCHPAD 8 FINAL CALL DISALLOW PARALLEL
41
SQL Create Function Statement
General Parameter Style Return Values as Normal (on PI) All Input/Output Parameters DB2SQL Parameter Style All Input Parameters All Output Parameters Null Indicators for all Input Parameters Null Indocators for all Output Parameters SQL STATE Function Name Specific Name Message Text Scratch Pad Data Final Flag These parameters are required by the format, but may not need to be used.
42
SQL Functions with RPGLE
Scratch Pad Data Selected SQL Function Data Returned Data Selected SQL Function Scratch Pad Data Data Returned Data Selected SQL Function Data Returned INSTRUCTOR NOTES This will be a quick review of this tool. It will not be covered in depth.
43
SQL Functions with RPGLE
Final Call Final Flag -1 1 Data Selected SQL Function Data Returned Data Selected SQL Function Data Returned Data Selected SQL Function Data Returned INSTRUCTOR NOTES This will be a quick review of this tool. It will not be covered in depth.
44
Functions Any Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.