58
SQL Routines – Getting to Know SQL PL Christopher J. Crone - IBM Distinguished Engineer, DB2 for z/OS [email protected]

SQL PL Basics

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: SQL PL Basics

SQLRoutines–GettingtoKnowSQLPL

ChristopherJ.Crone-IBMDistinguishedEngineer, DB2forz/[email protected]

Page 2: SQL PL Basics

SQLPLRoutines– TheBasics

[email protected]:M9ThursdaySeptember15th,2016|Platform:DB2forz/OS

Page 3: SQL PL Basics

Agenda

• Introduction• Languageelementsthroughanexample• ApplicationLifecycleDevelopment• SQLScalarandTableFunctions• SQLPLTriggers• Summary

Page 4: SQL PL Basics

INTRODUCTION

3

Page 5: SQL PL Basics

SQLPLHistory• DB25

• SQLPL(external)introduced

• DB26• SQLScalarFunctions

• DB29• NativeSQLPLProcedures

• DB210• NativeSQLPLFunctions• SQLTABLEFunctions• XMLand(non-LOB)DISTINCTTYPEsupport

• DB211• ARRAYDataType• AutonomousSQLPLProcedures

• DB212• NativeSQLPLTriggers• Constants

4

Page 6: SQL PL Basics

IntroductiontoSQLstoredprocedures

• WhatisanSQLstoredprocedure• AstoredprocedurethatcontainsonlySQLstatements• MayuseSQLcontrolstatementstowritethelogicpartoftheprogram

(WHILE,IF,etc.)• SQLProceduralLanguageor SQLPL

• TwotypesofSQLprocedures• External SQLprocedures(fromV5on)- GeneratedCprogramwhich

runsinaWLMenvironment• Native SQLprocedures(fromDB29)- TheSQLprocedurelogicrunsin

theDBM1addressspace

Page 7: SQL PL Basics

ExternalandnativeSQLprocedurescomparison

External Native

Multi-step (Precompile, compile, link-edit, BIND, DDL)

Requires C compiler

Single stepDDL

Requires WLM environment, load module

Runs entirely within the DB2 engine

Preparation

Execution

Page 8: SQL PL Basics

DB2z/OSStoredProcedureProcessing(External)

WLM//STEPLIB DD SP1 Load

module

z/OSAppl pgm

CALL SP1

DB2 DBM1 WLM DDF

sched SP1

EDMpool

Appl pgm

CALL SP1

SP1logic(load

module)

SP1 pkgDB2 directory

SP1pkg

Page 9: SQL PL Basics

NativeSQLPLRoutineProcessing(Native)z/OSAppl pgm

CALL SP1

DB2DBM1

DDF

Appl pgm

CALL SP1

SQL PL native logicSQLSQL

SP1DB2

directory

EDM pool

SQL PL native logicSQLSQL

SP1

SQLPLRoutine=Procedure(9),Function(10),Trigger(12)

• Priority of calling application (not DBM1 priority)• ASUTIME is still a safeguard for runaway logic

Page 10: SQL PL Basics

WhentousenativeSQLroutines

• Goodwhen…• SQLintensive• Containsminimalapplicationlogic• Lowestbillablecost(DRDAexecutioniszIIP eligible)andproductivityarethemostimportantpriorities

• Badwhen…• Containssignificantamountofapplicationlogic• ManyIF/WHILE/CASE/REPEATstatements• Executesmath,string,filemanipulationfunctions

Page 11: SQL PL Basics

DB2forz/OSV11Language/APICPUCostComparison forIRWWWorkloadLanguage/API Base CPU/Tran Cost Billable CPU/Tran Cost

after zIIP redirect

COBOL Stored Proc 1X (BASE) 0.74x

C Stored Proc 1.02x 0.75x

SQLJ Stored Proc 1.71x 1.16x

JDBC Stored Proc 2.19x 1.54x

Native SQL Stored Proc 1.07x 0.47x

Note : Stored Procedures called from IBM Type 4 JCC driver Client

zIIP benefit is applicable only for remote Store Procedures called via TCP/IP DRDA

Page 12: SQL PL Basics

LANGUAGEELEMENTS

11

Page 13: SQL PL Basics

LanguageElements- Anexample-- Declare handlers DECLARE EXIT HANDLER FOR SQLEXCEPTION GET DIAGNOSTICS CONDITION 1

p_sqlcode=DB2_RETURNED_SQLCODE, p_sqlstate = RETURNED_SQLSTATE;

-- Handler for duplicate condition DECLARE CONTINUE HANDLER FOR c_duplicateSET v_duplicate = 1;

-- SQL stmt, SQL control stmt-- Try insert, if duplicate, then update INSERT INTO department ( deptno,deptname)

VALUES ( p_deptno ,p_deptname );

IF v_duplicate = 1 THEN UPDATE department SET deptname = p_deptnameWHERE deptno = p_deptno;

END IF; END iud

CREATE PROCEDURE insert_update_department ( IN p_deptno CHAR(3) ,IN p_deptnameVARCHAR(29),OUT p_sqlstate CHAR(5) ,OUT p_sqlcode INT )

LANGUAGE SQL ASUTIME LIMIT 10DISALLOW DEBUG MODE iud: BEGIN

-- ROUTINE BODY-- Declare variables DECLARE v_duplicate INT DEFAULT 0;

-- Declare condition DECLARE c_duplicate CONDITION FOR SQLSTATE '23505';

-- Declare cursor if any

Page 14: SQL PL Basics

DB29- NewfeaturesforNativeSQLRoutines• Moredatatypes(BIGINT,BINARY,VARBINARY,DECFLOAT)areintroducedinDB29

• FORloop• Executesoneormultiplestatementsforeachrowofatable

BEGINDECLARE fullname CHAR(40);

FOR v1 ASc1 CURSOR FOR

SELECT firstnme, midinit, lastnameFROM employeeDO

SET fullname = lastname CONCAT ‘, ‘

CONCAT firstnmeCONCAT ‘ ‘CONCAT midinit ;

INSERT INTO TNAMES VALUES ( fullname ) ;END FOR ;

END;

Page 15: SQL PL Basics

Nameresolution• Rulesfornameresolutioninnativedifferentfromexternal• SQLparameterorSQLvariablecanhavethesamenameasa

columnnameleadingtoambiguityeg.dept isbothaSQLvariableandacolumninthetableemp• Externalwillmatchdept toSQLvariabledept• Nativewillmatchdept tocolumnemp.dept

CREATE PROCEDURE . . . BEGIN;

DECLARE dept CHAR(3); DECLARE x CHAR(3);

:DECLARE c1 CURSOR FOR

SELECT dept INTO x FROM emp ;:

END ;

Page 16: SQL PL Basics

Nameresolution• BESTPractices-

• Qualifycolumnnameswithtablenames• QualifySQLparametersbyprocedurename• QualifySQLvariablesbylabelofthecompoundstatement.

CREATE PROCEDURE . . . STEP1: BEGIN;

DECLARE dept CHAR(3); DECLARE x CHAR(3); DECLARE y CHAR(3); :

DECLARE c1 CURSOR FOR SELECT

STEP1.dept, emp.deptINTO x,yFROM emp ;

:END STEP1;

Page 17: SQL PL Basics

Compoundstatements• AcompoundstatementcontainsablockofSQLstatementsand

declarationsforSQLvariables,cursors,conditionnamesandconditionhandlers

• InDB2V8,notpossibletonestcompoundstatementswithinanSQLprocedure(whichmeantnoteveninconditionhandlers)

• InDB29,nestedcompoundstatementscanbeusedtodefinedifferentscopesforSQLvariables,cursors,conditionnames,andconditionhandlers.

Page 18: SQL PL Basics

CompoundStatements- Scoping• Anexample:

• Labelscanalsobeusedtojumptothebeginningorendofcompoundstatements.

CREATE PROCEDURE show_compound (OUT p_WorkerID INT) LANGUAGE SQL

l1: BEGIN -- Declare variables DECLARE v_ID INT; -- (1) -- New compound statement l2: BEGIN

-- Declare variables DECLARE v_ID INT; -- (2) -- Procedure logic SET l1.v_ID = 1; -- (3) SET l2.v_ID = 2; -- (4) SET v_ID = 3; -- (5) SET p_WorkerID = l2.v_ID; -- (6)

END l2; END l1

Page 19: SQL PL Basics

Conditionhandlers

• Storedprocedurewithoutanyerrorcheckingterminatesonanerrorunlessyouincludehandlerstotakeaction

• Aconditionhandler isanSQLstatementthatisexecutedwhenaspecifiedconditionisencounteredbyastatementwithintheprocedurebody.

• Scope– compoundstatementinwhichitisdeclared

• GeneralconditionsinDB2- SQLEXCEPTION,SQLWARNINGandNOTFOUND

• Types:• Exithandlers – willexecutestatementsinthehandlerandwillcontinueatthe

endofcompoundstatementitwasdeclaredin• Continuehandlers – willcontinueexecutionatthestatementfollowingtheone

thatraisedtheexception

Page 20: SQL PL Basics

Conditionhandlers• Generalform:

• Conditionnames:

• MultiplestatementsdefinedinahandlerbodyinanexternalSQLprocedurebyusingacontrolstatementotherthanacompound-statement

CREATE PROCEDURE ...BEGINDECLARE EXIT HANDLER FOR SQLEXCEPTIONIF (1=1) THENstmt1stmt2

END IF;rest of procedure body

DECLARE EXIT HANDLER FOR SQLSTATE '23503' ...;

DECLARE FOREIGN_KEY_VIOLATION CONDITION FOR SQLSTATE '23503';DECLARE EXIT HANDLER FOR FOREIGN_KEY_VIOLATION ...;

DECLARE handler-type HANDLER FOR condition SQL-procedure-statement

Page 21: SQL PL Basics

CompoundConditionhandlers• NativeSQLproceduresallowcompoundstatementsin

conditionhandlers

• InnativeSQLprocedures,SQLCODEandSQLSTATEvalueswillberesetafterexecutingtheIFclause

• AlsocheapertorunBEGIN/ENDvs.IF/ELSElogic

DECLARE EXIT HANDLER FOR NOT FOUND BEGIN

INSERT INTO ERR_TABLE(‘Error in stored proc’); SIGNAL SQLSTATE '70001’; SET MESSAGE_TEXT = 'Exit handler for not found fired';

END;

Page 22: SQL PL Basics

SQLPLprocedurethatsimulatesMERGElikefunction-- Handler for duplicate condition DECLARE CONTINUE HANDLER FOR c_duplicateSET v_duplicate = 1;

-- SQL stmt, SQL control stmt-- Try insert, if duplicate, then update

INSERT INTO department ( deptno,deptname) VALUES ( p_deptno,p_deptname );

IF v_duplicate = 1 THEN UPDATE department

SET deptname = p_deptnameWHERE deptno = p_deptno;

END IF; END iud

CREATE PROCEDURE insert_update_department( IN p_deptno CHAR(3) ,IN p_deptnameVARCHAR(29),OUT p_sqlstate CHAR(5) ,OUT p_sqlcode INT )

LANGUAGE SQL ASUTIME LIMIT 10DISALLOW DEBUG MODE iud: BEGIN -- ROUTINE BODY-- Declare variables DECLARE v_duplicate INT DEFAULT 0;-- Declare condition DECLARE c_duplicate CONDITION FOR SQLSTATE '23505';

-- Declare cursor if any

-- Declare handlers

DECLARE EXIT HANDLER FOR SQLEXCEPTION

GET DIAGNOSTICS CONDITION 1p_sqlcode = DB2_RETURNED_SQLCODE, p_sqlstate = RETURNED_SQLSTATE;

Page 23: SQL PL Basics

SQLPLenahcements – DB212

• AnSQLPLConstantissimplyavariable,thatisgivenavaluethatcannotbechanged.• DECLARE v_duplicate INT CONSTANT 0;

Page 24: SQL PL Basics

APPLICATIONLIFECYCLEDEVELOPMENT

23

Page 25: SQL PL Basics

MigratingexternalSQLprocedurestonative

• Noautomaticorforcedmigration• BothtypescanexistonsameDB2

• DistinctionmadeatCREATEPROCEDUREtime• BothtypeshaveLANGUAGESQL

• Externalshouldhaveoneorbothoffollowing:• FENCED• EXTERNALNAME

• Short(incomplete)answer• DROPtheexistingexternalSQLprocedure• CREATEthenewnativeSQLprocedure

Page 26: SQL PL Basics

MigrationConsiderations– External->NativeReviewsourcelogic toaddressanyincompatibilities(listedunder"ApplicationandSQLreleaseincompatibilities"inDB29InstallationGuide):• Errorhandling:

• Unhandledwarningsreturnedtocallerinnative(notinexternal)• Inexternalandnative,SQLCODEandSQLSTATEareconstantlybeingupdated.

Everystatementexecuted(SQLstatementandSQLcontrolstatementotherthancompoundandGETDIAGNOSTICS)resetsdiagnosticsareaandSQLCODE/SQLSTATE.Nativefollowsthisrigorously,whileexternalislessrigorous(whichwasexploited).

• AbetterpracticeistostopusingtheSQLCODEandSQLSTATEvariablesentirely.UseGETDIAGNOSTICSstatementinconditionhandlers,assigningDB2_RETURNED_SQLCODEandRETURNED_SQLSTATEtoothervariables.Useothervariablesforreference.

• Compoundstatementallowedinnativeconditionhandlers.ReplaceSQLcontrolstatement(IF,LOOP,etc.)usedtoenablemultipleSQLstatementsinconditionhandlerswithBEGIN..END.

• Nameresolutionrulesdifferentinnative.Explicitlyqualifynon-uniqueSQLparameters,SQLvariablesandcolumns

Page 27: SQL PL Basics

VersioningforProcedures• Versioning priortoDB29 - Loadmodulemanagement,no2entrieswith

sameprocedureandschema

• VersioninginnativeonDB29• newVERSION optiononCREATEandALTER,somultipleversionscanbe

created/addedforthesamestoredprocedure(withthesameschemaname)

• Selectingaversiontoexecute• CURRENTROUTINEVERSION(specialregister)

• e.g.,usefulforquicktestafterdeployment• nocatalogcaching

• ActiveVERSION(specifiedinthecatalog)• default• catalogcaching(sameasbefore)

CREATE PROCEDURE MEDIAN_RESULT_SET (OUT medianSalary DECIMAL(7,2))VERSION 22APR10DYNAMIC RESULT SETS 1

BEGIN……..END

Page 28: SQL PL Basics

Debugging• NativeSQLprocedurescanbedebuggedusingUnifiedDebugger

technology• UnifiedDebuggerisincludedinIBMOptim DevelopmentStudioor

MicrosoftVisualStudio• Allows– viewsource,setbreakpoint,view/changevariablevalues• DEBUGMODEonCREATEandALTERdetermineswhetherprocedure

canbedebuggedornot• AlternativeinAPARPI44721(DB211)– DBMS_OUTPUT.PUT…

Native procedures in DISALLOWstate

Native procedures in ALLOW state

Native procedures in DISABLE state

ALTER to DISALLOW

ALTER to ALLOW

ALTER to DISABLE

ALTER to DISABLE

Page 29: SQL PL Basics

Deployment• DeploymentofnativeSQLproceduresisdoneviaBINDPACKAGE…DEPLOY• EnablesyoutoaddorreplaceaversionofanativeSQLprocedureonthetargetremote

subsystemfromthecurrent-locationsubsystem• Example:

• BINDstoadifferentsubsystem(likeremotebind)– butdifferentfromremoteBIND• logicoftheprocedurebodystoredasaspecialsectioninthepackagewill

notberebound,onlySQLDMLwillgetnewaccesspathsatserver• Customersdonotneedtoworryaboutunexpectedbehaviorchangeafter

deployment• RequiresDRDAconnectionsbetweensystems

• Alternative isPM29226technique(SeeBackupCharts)

CREATE PROCEDURE OWNER1.MYPROC VERSION V1 ...BEGIN...ENDBIND PACKAGE (SERVER2.OWNER2) DEPLOY (OWNER1.MYPROC)

COPYVER(V1) ACTION(ADD) QUALIFIER(XYZ)

Page 30: SQL PL Basics

SQLSCALAR&TABLEFUNCTIONS

Page 31: SQL PL Basics

SQLPLsupportinscalarfunctions– BeforeDB210• User-definedfunctions

• External• Hostlanguageforlogic+SQL• Package• Returnsonevalueortable

• Non-external(SQL)• Inlinescalarfunction(definitionisactuallyinSYSVIEWS)• LanguageSQL• Returnsonevalue• Singlestatement(RETURNexpression)• Nopackage(worksmorelikeaview– inlineprocessing)

CREATE FUNCTION TAN (X DOUBLE) RETURNS DOUBLELANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC RETURN SIN(X)/COS(X)

Page 32: SQL PL Basics

SQLPLsupportinscalarfunctions– DB210• EnhancedSQLScalarFunctions inNFM

• MaycontainlogicusingSQLPLcontrolstatements• Non-inline,package• Parserdeterminestypeofscalarfunction• Limitation– noDDLinsidefunction• Example:reversesastringCREATE FUNCTION REVERSE(INSTR VARCHAR(20)) RETURNS VARCHAR(20) DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL BEGIN

DECLARE REVSTR, RESTSTR VARCHAR(20) 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

Page 33: SQL PL Basics

SQLSourcedFunctions

• Auser-definedfunctionthatisbasedonanexistingfunction.• ForExample

• CREATEFUNCTIONMYCENTER(INTEGER,INTEGER)RETURNSFLOATSOURCESMITH.CENTER(INTEGER,FLOAT);

• CREATEFUNCTION"-"(INCOME,EXPENSES)RETURNSDECIMAL(8,2)SOURCE"-"(DECIMAL,DECIMAL)

Page 34: SQL PL Basics

Syntaxcompatibilityproblem

SELECT CURRENT TIMESTAMP + 1 DAY FROM SYSIBM.SYSDUMMY1;

+----------------------------+ | | +----------------------------+

1_| 2008-12-05-14.03.44.883486 | +----------------------------+

SELECT CURRENT TIMESTAMP + 1 FROM SYSIBM.SYSDUMMY1;

RESULT OF SQL STATEMENT: DSNT408I SQLCODE = -171, ERROR: THE DATA TYPE, LENGTH, OR VALUE OF ARGUMENT 2 OF + IS INVALID

Page 35: SQL PL Basics

CreateanSQLFunction

CREATE FUNCTION ADD_TIME (TS TIMESTAMP, NUM_DAYS INTEGER) RETURNS TIMESTAMP LANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC RETURN TS + NUM_DAYS DAYS;

Page 36: SQL PL Basics

CreateanSQLSourcedFunction

CREATE FUNCTION "+" (TIMESTAMP,INTEGER)RETURNS TIMESTAMP SOURCE ADD_TIME(TIMESTAMP,INTEGER);

Page 37: SQL PL Basics

EnablesvendordependentsyntaxSELECT CURRENT TIMESTAMP + 1 DAY FROM SYSIBM.SYSDUMMY1;

+----------------------------+ | | +----------------------------+

1_| 2008-12-05-14.28.06.198339 | +----------------------------+

SELECT CURRENT TIMESTAMP + 1 FROM SYSIBM.SYSDUMMY1;

+----------------------------+ | | +----------------------------+

1_| 2008-12-05-14.28.06.492651 | +----------------------------+

Page 38: SQL PL Basics

CreateacompoundfunctionCREATE TABLE T1 (C1 VARCHAR(40)); INSERT INTO T1 VALUES (SPACE(5) || CHAR(CURRENT TIMESTAMP)); SELECT * FROM T1;

+-----------------------------------------+1_| 2009-01-04-17.00.02.022971 |

+-----------------------------------------+

SELECT TIMESTAMP(C1) FROM T1; DSNT408I SQLCODE = -180, ERROR: THE DATE, TIME, OR TIMESTAMP VALUE IS

INVALID

SELECT TIMESTAMP(STRIP(C1,BOTH)) FROM T1;

+----------------------------+ 1_| 2009-01-04-17.00.02.022971 |

+----------------------------+

Page 39: SQL PL Basics

CreateacompoundfunctionSET CURRENT SCHEMA = 'TEST';

CREATE FUNCTION TIMESTAMP (VC VARCHAR(40)) RETURNS TIMESTAMP LANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC

RETURN TIMESTAMP(STRIP(VC,BOTH));

SELECT TEST.TIMESTAMP(C1) FROM T1; +----------------------------+

1_| 2009-01-04-17.00.02.022971 | +----------------------------+

SET CURRENT PATH = TEST, SYSIBM, SYSFUN, SYSPROC;

SELECT TIMESTAMP(C1) FROM T1; +----------------------------+

1_| 2009-01-04-17.00.02.022971 | +----------------------------+

Page 40: SQL PL Basics

SQLScalarFuncctions andDATE/TIMESpecialRegisters

Beawareoftheusageofdate-timespecialregistersintheSQLscalarfunctionbody.ForinlineSQLscalarfunction(andalsoforSQLtablefunction),allreferencestoanydate-timespecialregisterreturnthesamevalue,andthisvalueisalsothesamevaluethatisretunedbythespecialregisterreferenceinthestatementthatinvokedthefunction.

BothreferencestoCURRENTTIMESTAMPwithinthebodyoftheinlineSQLscalarfunctionreturnthesamevalueastheCURRENTTIMESTAMPreferenceintheinvokingstatement.Inaddition,thetworeferencestoCURRENTTIMESTAMPwithinthebodyofthenon-inlineSQLscalarfunctionreturndifferentvalues,whicharealsodifferentfromtheCURRENTTIMESTAMPreferenceintheinvokingstatement 39

Page 41: SQL PL Basics

Example:CreatetwofunctionsthatreferenceCURRENTTIMESTAMPCREATE FUNCTION TMS_INLINE()RETURNS CHAR(56) LANGUAGE SQL NO EXTERNAL ACTIONRETURN

CHAR(CURRENT TIMESTAMP) || -- get timestampUPPER(LOWER(SPACE(POWER(1,2))||'-- ' )) || -- waste some timeCHAR(CURRENT TIMESTAMP)# -- get timestamp

-- create similar non-inline SQL scalar functionCREATE FUNCTION TMS_NONINLINE()RETURNS CHAR(56) LANGUAGE SQL NO EXTERNAL ACTIONBEGIN

DECLARE VAR1,VAR2 CHAR(26);SET VAR1 = CHAR(CURRENT TIMESTAMP); -- get timestamp-- some time will pass before the next statement is processedSET VAR2 = CHAR(CURRENT TIMESTAMP); -- get timestampRETURN VAR1 || ' -- ' || VAR2;

END#

40

Page 42: SQL PL Basics

Invokeboththefunctionswejustcreated-- nowinvokebothfunctionsSELECT CURRENT TIMESTAMP AS Invoker

,TMS_INLINE() AS Inline,TMS_NONINLINE() AS NonInline

FROM SYSIBM.SYSDUMMY1#-- result:-- Invoker:2010-08-01-17.30.01.295158-- Inline:2010-08-01-17.30.01.295158-- 2010-08-01-17.30.01.295158-- NonInline:2010-08-01-17.30.01.296383 -- 2010-08-01-17.30.01.296468BothreferencestoCURRENTTIMESTAMPwithinthebodyoftheinlineSQLscalarfunctionreturnthesamevalueastheCURRENTTIMESTAMPreferenceintheinvokingstatement. Inaddition,thetworeferencestoCURRENTTIMESTAMPwithinthebodyofthenon-inlineSQLscalarfunctionreturndifferentvalues,whicharealsodifferentfromtheCURRENTTIMESTAMPreferenceintheinvokingstatement.

41

Page 43: SQL PL Basics

SQLTablefunctions

InDB210,thebodyofanSQLtablefunctioncanbewrittenentirelyinSQLPL.

DB210forz/OSintroducessupportforsimpleSQLtablefunctionsinthesensethatyoucanuseasingleRETURNcontrolstatementinthefunctionbody.WhenyoudefineaSQLtablefunctionyoucan:DefineparameterasadistincttypeDefineparameterforatransitiontable(TABLELIKE...ASLOCATOR)IncludeasingleRETURNSQLcontrolstatementthatreturnsaresulttable

42

Page 44: SQL PL Basics

ExampleSQLTableFunctionCREATE FUNCTION TRYTABLE(P1 CHAR(3))RETURNS TABLE(FIRSTNAME VARCHAR(12),

LASTNAME VARCHAR(15))RETURN SELECT FIRSTNME, LASTNAME FROM DSN8A10.EMP WHERE WORKDEPT = P1;

SELECT * FROM TABLE(TRYTABLE('A00')) X;+--------------------------------+| FIRSTNAME | LASTNAME |+--------------------------------+| CHRISTINE | HAAS || VINCENZO | LUCCHESI || SEAN | O'CONNELL || DIAN | HEMMINGER || GREG | ORLANDO |+--------------------------------+ 43

Page 45: SQL PL Basics

SQLPLTRIGGERS

44

Page 46: SQL PL Basics

§ Only allows limited SQL statements inside the trigger body§ No control statements allowed (ex: IF-THEN/ELSE,

LOOP, REPEAT)§ Must explicitly CALL a procedure in the trigger body if

the trigger needs complicated control logic § Cannot port trigger from other DBMS if trigger body

contains control statements§ No DEBUGGER Support§ Single VERSION only. Requires DROP and CREATE if

trigger needs to be changed – affecting trigger activation order

§ Optimized for fast execution, small and compact

Traditional Triggers

Page 47: SQL PL Basics

• Rich capability in trigger body• Allow SQL PL control statements

• IF-THEN-ELSE, LOOP, REPEAT, …• Allow more SQL statements, dynamic SQL, variables,

handlers• Easier porting of triggers from other DBMSes• DEBUGGER support• VERSIONs support

• Provides a better way to change a trigger w/o DROP, CREATE

• Can change trigger online and maintain trigger activation order

• Richer capability means some performance overhead compared to an equivalent traditional trigger

DB2 12 SQL PL Triggers

Page 48: SQL PL Basics

TRADITIONAL TRIGGERBEGIN ATOMIC/END is the existing syntax for the old trigger

CREATE TRIGGER validate_schedNO CASCADE BEFOREMODE DB2SQLINSERT ON class_schedREFERENCING NEW AS nFOR EACH ROW WHEN (n.ending IS NULL OR n.ending > '21:00')

BEGIN ATOMICSET n.ending = n.starting + 1 HOUR;

END

SQL PL TRIGGER BEGIN/END for New SQL PL trigger

CREATE TRIGGER validate_schedNO CASCADE BEFORE INSERT ON class_schedREFERENCING NEW AS nFOR EACH ROW WHEN (n.ending IS NULL OR n.ending > '21:00')

BEGIN IF (n.ending IS NULL) THEN

SET n.ending = n.starting + 1 HOUR;END IF;IF (n.ending > '21:00') THEN

SIGNAL SQLSTATE '80000'SET MESSAGE_TEXT =

'class ending time is at or beyond 9pm';END IF;

END

o Same syntax for the old trigger to ensure no application migration performance impact MODE DB2SQL

o New syntax for SQL PL trigger (BEGIN/END) upon trigger creationo SQL PL Triggers can replace a traditional trigger that calls a SP to execute logic. This

would perform better and result in one package rather than two (trigger package and SP package) being loaded.

Page 49: SQL PL Basics

SUMMARY

Page 50: SQL PL Basics

Summary

• NativeSQLPLRoutinesarewellsuitedforSQLintensiveapplications

• Offersbenefitsinmostscenarios(reducedcost,increasedperformance,easierdevelopmentandmaintenance)

• IfyouarealreadyusingexternalSQLproceduresonDB29,migrationtonativesql procedureisworthwhile(performanceandzIIP offload)

• ConsidernativeSQLPLroutinesforSQLintensivenewapplicationdevelopment

Page 51: SQL PL Basics

ThankYou

50

[email protected]:M9ThursdaySeptember15th,2016|Platform:DB2forz/OS

Page 52: SQL PL Basics

BACKUP

51

Page 53: SQL PL Basics

References

• RedbookSG24-7604:ThroughtheCALLandbeyond availableatwww.ibm.com/redbooks

• “DB2SQLPLEssentialGuideforDB2UDBonLinux,UNIX,Windows,i5/OS,andz/OS"2ndedition2005(ISBN0-13-147700-5)

• DB2forz/OSTechnicalOverview– SG24-7892

• DB2forz/OSTechnicalOverview- SG24-8180

Page 54: SQL PL Basics

Relevantzparms/settings

• Zparms thatcancontrolinstancerelatedstorageissues• MAX_ST_PROC – controlsthenumberofstoredprocedureinstancesin

onethread• MAX_NUM_CUR – controlsthenumberofcursorsthatcanbeopened

inonethread

• Lessrelevantwithnative(unlessinDEBUGmode)• WLMENV - nameofWLM_ENVIRONMENTtouseforstoredprocedure• NUMTCB - foraWLMstoredprocedure,howmanySQLCALL

statementscanbeprocessedconcurrentlyinoneaddressspace

Page 55: SQL PL Basics

Sourcecodemgmt&Deploymentproblem

• AfterwidespreadadoptionofSQLPL,customersrunningintooperationalissuesinmanagingSQLPLapplications• Sourcecodemanagement

• NogoodwaytoholdsourcecodeoutsideofDB2• Deployment

• BINDPACKAGEDEPLOY• NeedsDRDA• Canchangeonlyfewpropertiesattargetserver(QUALIFIER,SCHEMA)• PropertieslikePATH,VALIDATEcannotbechangedontargetserver

• ManyformsofDDL,difficulttoknowwhichoneneeded• CREATEPROC• ALTERPROCADDVERSION/REPLACEVERSION

Page 56: SQL PL Basics

Sourcecodemgmt&Deploymentsolution

• V9APARPM29226distributesthesetofSQLPLsourcecodemanagementservices• UpgradestheV10DB2samplejobDSNTEJ67toexploitthenewservices• DemonstratestheexternaltonativeSQLPLmigrationprocess• ExtractanexternalSQLproctofile,sourcedeploysanativeSQLSPthat

generatesnativeoptions,modifytheSQLprocsourcefile,produceanativeSQLPLlisting.

Page 57: SQL PL Basics

Sourcecodemgmt&Deploymentsolution

• ProvideSQLPLSourceDeployment capability

• IntroduceasetofsampleREXXservices thatcancombinetoperformthesebasicSQLPLchangemanagementprocesses:• SQLPLsourceextraction(toafile,toastring)SQLPLSRC DB2TDEV.VDRSP1 'DBA.UNIT.SPSRC(VDRSP1)' NORM• SQLPLsourcetransformationandmodification

(ChangetheDDLverbform,schema,version,andoptions)SQLPLTRN DD:SRC1 DD:SRC2 CP TEST V5 SQL PATH DB2TEST• SQLPLsourcedeployment(fromafile,fromastring)CRSQLPL 'DBA.UNIT.SPSRC(VDRSP1)' DB2PROD VALIDATE RUN

• ReplacesBINDDEPLOYusageorcomplementsit

Page 58: SQL PL Basics

Sourcecodemgmt&Deploymentsolution

• Provideflexibilitytoenablecustomercustomization,tomix&matchservices,toadapttotheirownconventionsandpolicies.Support:• JCLbasedprocesses(integrationwithmainframeSCMs)• Remoteaccess(integrationwithworkstationSCMs)

• AdditionalREXXservicesincluded,enablingthebasiccodemanagementprocesses,andusefulforcustomoralternativeprocesses:• SQLPLfiletransforms(V-format,F-format,HFS)• SQLPLlistingservices(precompiler)• SQLPLsourcedescriptionservice(TOCusedforediting)• StoredProcedureCALLservice(DSNREXX)• Connectionservices(REXXstandalone,REXXsubroutineorREXXSP)