Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
SQLRoutines–GettingtoKnowSQLPL
ChristopherJ.Crone-IBMDistinguishedEngineer, DB2forz/[email protected]
SQLPLRoutines– TheBasics
[email protected]:M9ThursdaySeptember15th,2016|Platform:DB2forz/OS
Agenda
• Introduction• Languageelementsthroughanexample• ApplicationLifecycleDevelopment• SQLScalarandTableFunctions• SQLPLTriggers• Summary
INTRODUCTION
3
SQLPLHistory• DB25
• SQLPL(external)introduced
• DB26• SQLScalarFunctions
• DB29• NativeSQLPLProcedures
• DB210• NativeSQLPLFunctions• SQLTABLEFunctions• XMLand(non-LOB)DISTINCTTYPEsupport
• DB211• ARRAYDataType• AutonomousSQLPLProcedures
• DB212• NativeSQLPLTriggers• Constants
4
IntroductiontoSQLstoredprocedures
• WhatisanSQLstoredprocedure• AstoredprocedurethatcontainsonlySQLstatements• MayuseSQLcontrolstatementstowritethelogicpartoftheprogram
(WHILE,IF,etc.)• SQLProceduralLanguageor SQLPL
• TwotypesofSQLprocedures• External SQLprocedures(fromV5on)- GeneratedCprogramwhich
runsinaWLMenvironment• Native SQLprocedures(fromDB29)- TheSQLprocedurelogicrunsin
theDBM1addressspace
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
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
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
WhentousenativeSQLroutines
• Goodwhen…• SQLintensive• Containsminimalapplicationlogic• Lowestbillablecost(DRDAexecutioniszIIP eligible)andproductivityarethemostimportantpriorities
• Badwhen…• Containssignificantamountofapplicationlogic• ManyIF/WHILE/CASE/REPEATstatements• Executesmath,string,filemanipulationfunctions
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
LANGUAGEELEMENTS
11
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
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;
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 ;
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;
Compoundstatements• AcompoundstatementcontainsablockofSQLstatementsand
declarationsforSQLvariables,cursors,conditionnamesandconditionhandlers
• InDB2V8,notpossibletonestcompoundstatementswithinanSQLprocedure(whichmeantnoteveninconditionhandlers)
• InDB29,nestedcompoundstatementscanbeusedtodefinedifferentscopesforSQLvariables,cursors,conditionnames,andconditionhandlers.
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
Conditionhandlers
• Storedprocedurewithoutanyerrorcheckingterminatesonanerrorunlessyouincludehandlerstotakeaction
• Aconditionhandler isanSQLstatementthatisexecutedwhenaspecifiedconditionisencounteredbyastatementwithintheprocedurebody.
• Scope– compoundstatementinwhichitisdeclared
• GeneralconditionsinDB2- SQLEXCEPTION,SQLWARNINGandNOTFOUND
• Types:• Exithandlers – willexecutestatementsinthehandlerandwillcontinueatthe
endofcompoundstatementitwasdeclaredin• Continuehandlers – willcontinueexecutionatthestatementfollowingtheone
thatraisedtheexception
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
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;
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;
SQLPLenahcements – DB212
• AnSQLPLConstantissimplyavariable,thatisgivenavaluethatcannotbechanged.• DECLARE v_duplicate INT CONSTANT 0;
APPLICATIONLIFECYCLEDEVELOPMENT
23
MigratingexternalSQLprocedurestonative
• Noautomaticorforcedmigration• BothtypescanexistonsameDB2
• DistinctionmadeatCREATEPROCEDUREtime• BothtypeshaveLANGUAGESQL
• Externalshouldhaveoneorbothoffollowing:• FENCED• EXTERNALNAME
• Short(incomplete)answer• DROPtheexistingexternalSQLprocedure• CREATEthenewnativeSQLprocedure
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
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
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
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)
SQLSCALAR&TABLEFUNCTIONS
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)
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
SQLSourcedFunctions
• Auser-definedfunctionthatisbasedonanexistingfunction.• ForExample
• CREATEFUNCTIONMYCENTER(INTEGER,INTEGER)RETURNSFLOATSOURCESMITH.CENTER(INTEGER,FLOAT);
• CREATEFUNCTION"-"(INCOME,EXPENSES)RETURNSDECIMAL(8,2)SOURCE"-"(DECIMAL,DECIMAL)
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
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;
CreateanSQLSourcedFunction
CREATE FUNCTION "+" (TIMESTAMP,INTEGER)RETURNS TIMESTAMP SOURCE ADD_TIME(TIMESTAMP,INTEGER);
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 | +----------------------------+
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 |
+----------------------------+
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 | +----------------------------+
SQLScalarFuncctions andDATE/TIMESpecialRegisters
Beawareoftheusageofdate-timespecialregistersintheSQLscalarfunctionbody.ForinlineSQLscalarfunction(andalsoforSQLtablefunction),allreferencestoanydate-timespecialregisterreturnthesamevalue,andthisvalueisalsothesamevaluethatisretunedbythespecialregisterreferenceinthestatementthatinvokedthefunction.
BothreferencestoCURRENTTIMESTAMPwithinthebodyoftheinlineSQLscalarfunctionreturnthesamevalueastheCURRENTTIMESTAMPreferenceintheinvokingstatement.Inaddition,thetworeferencestoCURRENTTIMESTAMPwithinthebodyofthenon-inlineSQLscalarfunctionreturndifferentvalues,whicharealsodifferentfromtheCURRENTTIMESTAMPreferenceintheinvokingstatement 39
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
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
SQLTablefunctions
InDB210,thebodyofanSQLtablefunctioncanbewrittenentirelyinSQLPL.
DB210forz/OSintroducessupportforsimpleSQLtablefunctionsinthesensethatyoucanuseasingleRETURNcontrolstatementinthefunctionbody.WhenyoudefineaSQLtablefunctionyoucan:DefineparameterasadistincttypeDefineparameterforatransitiontable(TABLELIKE...ASLOCATOR)IncludeasingleRETURNSQLcontrolstatementthatreturnsaresulttable
42
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
SQLPLTRIGGERS
44
§ 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
• 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
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.
SUMMARY
Summary
• NativeSQLPLRoutinesarewellsuitedforSQLintensiveapplications
• Offersbenefitsinmostscenarios(reducedcost,increasedperformance,easierdevelopmentandmaintenance)
• IfyouarealreadyusingexternalSQLproceduresonDB29,migrationtonativesql procedureisworthwhile(performanceandzIIP offload)
• ConsidernativeSQLPLroutinesforSQLintensivenewapplicationdevelopment
BACKUP
51
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
Relevantzparms/settings
• Zparms thatcancontrolinstancerelatedstorageissues• MAX_ST_PROC – controlsthenumberofstoredprocedureinstancesin
onethread• MAX_NUM_CUR – controlsthenumberofcursorsthatcanbeopened
inonethread
• Lessrelevantwithnative(unlessinDEBUGmode)• WLMENV - nameofWLM_ENVIRONMENTtouseforstoredprocedure• NUMTCB - foraWLMstoredprocedure,howmanySQLCALL
statementscanbeprocessedconcurrentlyinoneaddressspace
Sourcecodemgmt&Deploymentproblem
• AfterwidespreadadoptionofSQLPL,customersrunningintooperationalissuesinmanagingSQLPLapplications• Sourcecodemanagement
• NogoodwaytoholdsourcecodeoutsideofDB2• Deployment
• BINDPACKAGEDEPLOY• NeedsDRDA• Canchangeonlyfewpropertiesattargetserver(QUALIFIER,SCHEMA)• PropertieslikePATH,VALIDATEcannotbechangedontargetserver
• ManyformsofDDL,difficulttoknowwhichoneneeded• CREATEPROC• ALTERPROCADDVERSION/REPLACEVERSION
Sourcecodemgmt&Deploymentsolution
• V9APARPM29226distributesthesetofSQLPLsourcecodemanagementservices• UpgradestheV10DB2samplejobDSNTEJ67toexploitthenewservices• DemonstratestheexternaltonativeSQLPLmigrationprocess• ExtractanexternalSQLproctofile,sourcedeploysanativeSQLSPthat
generatesnativeoptions,modifytheSQLprocsourcefile,produceanativeSQLPLlisting.
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
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)