735DB2Procedures

Embed Size (px)

Citation preview

  • 8/2/2019 735DB2Procedures

    1/24

    DB2 9.5 SQL Procedure Developer exam 735prep, Part 2: DB2 SQL proceduresSkill Level: Intermediate

    Marina Greenstein ([email protected])Executive IT SpecialistIBM

    Shakeb Shere ([email protected])

    IBM DB2 Common Client Technologies advanced support analystIBM

    02 Oct 2008

    This tutorial introduces the SQL procedure as it relates to DB2 V9.5. Learn aboutDB2 9.5 SQL procedures, including an introduction to stored procedures, theadvantages of using stored procedures, and the differences between SQLprocedures and external procedures. Learn about different SQL procedurestatements and see how to invoke and share nested stored procedures. Test anddeploy stored procedures and discover how to secure SQL procedures. This tutorialis the second in a series of six tutorials designed to help you prepare for the DB2 9.5SQL Procedure Developer Certification Exam (735).

    Section 1. Before you start

    About this series

    Thinking about seeking certification on DB2 SQL Procedure Developer (Exam 735)?If so, you've landed in the right spot. This series of six DB2 certification preparationtutorials covers all the basics -- the topics you'll need to understand before you readthe first exam question. Even if you are not planning to seek certification right away,this set of tutorials is a great place to start learning all about database developmentfor DB2 V9.5.

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 1 of 24

    mailto:[email protected]:[email protected]://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/mailto:[email protected]:[email protected]
  • 8/2/2019 735DB2Procedures

    2/24

    About this tutorial

    In this tutorial, you'll learn about DB2 9.5 SQL procedures, including an introductionto stored procedures, the advantages of using stored procedures, and the

    differences between SQL procedures and external procedures. Learn about differentSQL procedure statements and see how to invoke and share nested storedprocedures. Test and deploy stored procedures and discover how to secure SQLprocedures.

    This is the second in a series of six tutorials you can use to help prepare for the DB29.5 SQL Procedure Developer exam 735. The material in this tutorial primarilycovers the objectives in Section 2 of the test, which is entitled "SQL Procedures."See Resources.

    PrerequisitesThis tutorial is written for Linux, UNIX, or Windows database developers oradministrators, whose skills and experience are at a beginning to intermediate level.You should have a general familiarity with using a UNIX or Windows command-lineshell and a working knowledge of DB2 and SQL commands.

    System requirements

    The examples in this tutorial are specific to DB2 9.5 running on a Windows operating

    system. The concepts and information provided are relevant to DB2 running on anydistributed platform.

    You do not need a copy of DB2 9.5 to complete this tutorial. However, you will getmore out of the tutorial if you download the free trial version of IBM DB2 9.5 to workalong with this tutorial.

    Section 2. Stored Procedures

    What is a stored procedure?

    A stored procedure(also referred to as a routine) is a database object that containsa series of SQL statements and application control logic that can formulate business

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 2 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    3/24

    logic and are executed directly on the database server. The business logic getsencapsulated inside the stored procedure, and it can then be invoked from clientapplications, other stored procedures, user-defined functions or from triggers via anSQL statement. Stored procedures can accept parameter values to change thebehaviour of the business logic based on the input data. They can then return output

    values back to the caller or they can return multiple result sets to the caller.

    Stored procedures can be implemented using the SQL Procedure Language (SQLPL) or a programming language such as Java or C.

    Stored procedures can considerably improve the performance of a distributedapplication (an application running on a remote system) by:

    Reducing the amount of network traffic

    Reducing the coding efforts involved with application developers

    Providing a non-complex way of invoking a remote stored procedure from

    a distributed client

    Figure 1 shows a situation in which stored procedures are useful:Figure 1. Reducing network traffic by using stored procedures

    Advantages of using stored procedures

    The following benefits can be gained from using stored procedures:

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 3 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    4/24

    Simplifies code reuse, code standardization and code maintenance:

    A series of different applications that may all need to perform a similartask can be done quite easily by coding a single stored procedure toperform that task, and having each client application invoke that

    stored procedure so that task can be executed. If the task needs to bemodified, then only the affected stored procedure would need to bemodified, otherwise each application would need to be changed.

    Controlled access to other database objects:

    A user who does not possess the access privilege to a particulardatabase object or operation on a database (e.g., creating a table),but who wishes to perform action on that object or an operation, mayaccomplish his goal by invoking a stored procedure that he has theauthority to run. This means that privilege management can be

    simplified.

    Improving application performance:

    For remote applications, each SQL statement that is issued needs tobe transmitted through the network separately one at a time. This canresult in high levels of network traffic. By adding all of thesestatements inside a single stored procedure, only one networkrequest gets made by the client application to invoke that storedprocedure. This, of course, minimizes the amount of network trafficinvolved, and thus improves the overall performance of theapplication.

    More efficient SQL:

    Since stored procedures reside at the database server and areessentially database objects themselves, they have the ability toperform better than client applications because SQL requests aretransmitted much more efficiently. Stored procedures usingembedded SQL operations also have their access plans alreadystored in packages, thus improving the time it takes to execute eachstatement. If the stored procedure is created with the NOT FENCEDclause, then the stored procedure runs in the same process space as

    the database manager which allows communication to be done withinshared memory.

    Enhanced capabilities:

    Since a stored procedure resides on the database server, it tends tohave more access to memory and disk space then the application

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 4 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    5/24

    would. Applications have access to software that is installed on thedatabase server.

    Interoperability:

    Different code modules may be implemented in different programminglanguages by different programmers. To help achieve code reuse withthe interoperability of logic, stored procedures themselves can bewritten in different languages. A client application coded in a differentlanguage can invoke a stored procedure written in a differentlanguage (for example, a stored procedure written in Java can beinvoked from an application written in C++). Also stored procedureswritten in different languages can invoke each other (for example, astored procedure written in C can invoke a stored procedure written inJava). The operating system of the client and the operating system ofthe server where the stored procedure is located can also be different(for example, a Windows client application can invoke a storedprocedure running on AIX).

    Limitations of stored procedures

    There is an interoperability with invoking stored procedures, such that theclient application can be of a different programming language from thestored procedure. However, external stored procedures written in aspecific language would only work on certain platforms. For example, a

    CLR stored procedure can only function on a Windows-based platform.This stored procedure can be invoked from anywhere; however, if theserver is to be migrated to a different platform (for example, Solaris orAIX), then the stored procedure needs to be re-written. This would also betrue for stored procedures written in C, C++ or COBOL, where the storedprocedure would need to be re-compiled on the new server. SQLprocedures would not have this problem. Java stored procedures are alsomore flexible, but the new database server would need to have a JavaVirtual Machine (JVM) installed in order to execute the stored procedure.

    The only SQL statement that can invoke a stored procedure is the CALL

    statement. The CALL statement can be used from applications, storedprocedures, user-defined functions or triggers.

    Stored procedures are allowed to be nested such that one storedprocedure can call another stored procedure, which can then call anotherstored procedure. DB2 v9.5 has a maximum limitation of 64 storedprocedures that can be nested at one time.

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 5 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    6/24

    Stored procedures cannot preserve state between invocations.

    A stored procedure output parameter cannot directly be used with anotherSQL statement. The calling interface needs to assign the outputparameter to some variable, and then can use that variable with anotherSQL statement later on if it chooses to.

    Scrollable cursors are not supported with stored procedures.

    Differences between external stored procedures and SQLstored procedures

    There are two types of stored procedures that DB2 supports. External stored

    procedures and SQL procedures.

    External stored procedures have their logic defined in a programming languageapplication that exists outside of the database. The executable or library for this typeof stored procedure exists in the file system in which the database server is installed.The external stored procedure, like the SQL procedure, is registered with thedatabase, but during the registration process, the location of the stored procedureexecutable or library needs to be specified.DB2 supports external stored procedures in a variety of programming languagesincluding C, C++, COBOL, Java and .NET (also referred to as a CLR storedprocedure).The following features are unique to external stored procedures:

    External stored procedures allows access to non-database interfacessuch as the file system, or applications. They can use these resourceseven if they are not part of the database system specifically. As anexample, an external stored procedure can execute a shell script on aUNIX database server to run a specific task.

    External stored procedures use parameter styles to determine how acertain input, output, or input/output parameter is to be used by theprogramming language used for that stored procedure. Some parameterstyles allow the use of passing meta-data information such as database

    and stored procedure property information in a structure known as dbinfothat might be useful to the stored procedure.

    External stored procedures can be defined as FENCED or NOTFENCED. This determines if the stored procedure should run in the sameaddress space as the database manager (NOT FENCED), or if it shouldrun in its own process (FENCED). A stored procedure defined as NOT

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 6 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    7/24

    FENCED performs slightly faster since it does not need to communicateusing shared memory segments; however, they can be riskier. Anunfenced stored procedure can cause the database server to crash ifthere is a problem with the stored procedure since it will be using thesame address space as DB2. Java stored procedures must be defined as

    FENCED; however, they can be defined as THREADSAFE or NOTTHREADSAFE.

    The following features are unique to SQL procedures:

    SQL procedures are only written in SQL using a language called SQLProgramming Language (SQL PL). More information about this languagecan be found in the previous tutorial of this series (see Resources). So,the main difference between external stored procedures and SQLprocedures is that external procedures are coded using a specificprogramming language, whereas SQL procedures are coded using only

    SQL statements.

    SQL procedures reside in the actual database. Unlike external storedprocedures which have a dependency on an external library or executablethat exists in the file system, an SQL procedure is part of the database.

    Building an SQL procedure does not require a compiler or a deepunderstanding of a specific programming language. So the developmentof an SQL procedure might be quicker.

    SQL procedures are always defined as NOT FENCED. There is less risk

    involved with these types of stored procedures since only SQL operationscan be performed by the stored procedure limiting the risk involved withthe database server.

    SQL procedures are more portable. Since they do not rely on a specificprogramming language whose compiler or interpreter would be neededon each database server, it would be easier to re-create these storedprocedures on each server that needs them.

    Section 3. SQL procedure structure

    The SQL procedure structure consists of the CREATE PROCEDURE statement,parameters, and compound statement. The following pseudo-diagram shows the

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 7 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    8/24

    structure of an SQL procedure:

    Listing 1. Structure of an SQL procedure

    CREATE PROCEDURE proc_nameIN, OUT, INOUT parameters

    optional clausesSQL procedure body - compound statement

    The CREATE PROCEDURE statement defines the characteristics and logic of thestored procedure which is stored in the DB2 system catalogs (for example,SYSCAT.PROCEDURES).

    Listing 2. CREATE PROCEDURE command syntax

    CREATE PROCEDURE--procedure-name----------------------------->

    >--+----------------------------------------------------+--?---->

    '-(--+------------------------------------------+--)-'| .-,------------------------------------. || V .-IN----. | |'---+-------+--parameter-name--data-type-+-'

    +-OUT---+'-INOUT-'

    >--+-------------------------+--?------------------------------->'-SPECIFIC--specific-name-'

    .-DYNAMIC RESULT SETS 0--------. .-MODIFIES SQL DATA-.>--+------------------------------+--?--+-------------------+--->

    '-DYNAMIC RESULT SETS--integer-' +-CONTAINS SQL------+'-READS SQL DATA----'

    .-NOT DETERMINISTIC-. .-CALLED ON NULL INPUT-.>--?--+-------------------+--?--+----------------------+--?----->

    '-DETERMINISTIC-----'

    .-INHERIT SPECIAL REGISTERS-. .-OLD SAVEPOINT LEVEL-.>--+---------------------------+--?--+---------------------+---->

    '-NEW SAVEPOINT LEVEL-'

    .-LANGUAGE SQL-. .-EXTERNAL ACTION----.>--?--+--------------+--?--+--------------------+--?------------>

    '-NO EXTERNAL ACTION-'

    >--+------------------------------+--?-------------------------->'-PARAMETER CCSID--+-ASCII---+-'

    '-UNICODE-'

    >--| SQL-procedure-body|-------------------------------------->>-CALL--procedure-name--+--------------------------+---------->db2 call nest_diagn(?,?)

    Value of output parameters--------------------------Parameter Name : RET_CODE1Parameter Value : 2

    Parameter Name : RET_CODE2Parameter Value : 0

    Return Status = 0

    Please note that you need to DECLARE a variable that will be accepting the valuefrom DB2_RETURN_STATUS.

    Sharing data between stored procedures

    The previous examples show how stored procedures can share data usingparameters and the RETURN statement. Now, let's examine how 2 (or more) storedprocedures can share the same result set from a cursor.

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 14 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    15/24

    Procedure result_from_cursorgets a name, job description, commission andlocation for each worker from the STAFF and ORG tables for a particulardepartment:

    Listing 12. Example of procedure to return result set

    CREATE PROCEDURE result_from_cursor (deptin int)DYNAMIC RESULT SETS 1

    P1: BEGIN-- Declare cursorDECLARE cursor1 CURSOR WITH RETURN FOR

    SELECT a.name, a.job, COALESCE(a.comm,0),b.location

    FROM staff a, org bwhere a.dept = b.deptnumb

    AND a.dept = deptin;

    OPEN cursor1;END P1

    For example, for department 51, you get the following result set:

    Listing 13. Result set for department 51

    NAME JOB COMMISSION LOCATION--------- ----- --------------- -------------Fraye Mgr 0.00 DallasWilliams Sales 637.65 DallasSmith Sales 992.80 DallasLundquist Clerk 189.65 DallasWheeler Clerk 513.30 Dallas

    Now you want to use the result set from this stored procedure (without storing it intemporary or permanent table) in another stored procedure.

    DB2 permits an outer stored procedure to use a result set from an inner one. Here iswhat you need to do:

    Declare a result set locator using the following syntax:

    DECLARE rs_locator_var1 RESULT_SET_LOCATOR VARYING;

    Associate this result set locator with the calling procedure:

    ASSOCIATE RESULT SET LOCATOR( rs_locator_var1) WITH

    PROCEDURE proc_called;

    Allocate the cursor that points to the result set from the calling procedure:

    ALLOCATE cursor1 CURSOR FOR RESULT SETrs_locator_var1;

    The following example demonstrates all those methods:

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 15 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    16/24

    Listing 14. Using result set from nested procedure

    CREATE PROCEDURE Use_nested_cursor (deptin int, OUTtot_dept_comm DEC(12,2))

    BEGIN

    DECLARE sqlcode int default 0;DECLARE v_comm DECIMAL(12,2) DEFAULT 0.0;DECLARE v_name, v_location varchar(20);DECLARE v_job char(6);

    DECLARE LOC1 RESULT_SET_LOCATOR VARYING;

    SET tot_dept_comm = 0;CALL result_from_cursor(deptin);

    ASSOCIATE RESULT SET LOCATOR( LOC1) WITH PROCEDUREresult_from_cursor;

    ALLOCATE C1 CURSOR FOR RESULT SET LOC1;

    FETCH FROM C1 INTO v_name,v_job,v_comm,v_location;WHILE sqlcode = 0 DO

    SET tot_dept_comm = tot_dept_comm + v_comm;

    FETCH FROM C1 INTO v_name,v_job,v_comm,v_location;END WHILE;

    END

    Now, if you execute this stored procedure with department "51" as the inputparameter, you get the total department commission:

    Listing 15. Results when department 51 is an input parameter

    > call use_nested_cursor (51,?)

    Value of output parameters

    --------------------------Parameter Name: TOT_DEPT_COMMParameter Value: 2333.40

    Sharing data with global variables

    DB2 supports session global variables. A session global variable is associated witha specific session, is global for each stored procedure in that session, and containsa value that is unique to that session.

    The following diagram shows the syntax for the session global variable:

    Listing 16. CREATE VARIABLE syntax

    CREATE VARIABLE var_name DATATYPE [DEAFULT value];

    Please note that the session global variable is declared outside of a stored

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 16 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    17/24

    procedure, just like any other database object.

    The following script demonstrates the use of global variables:

    Listing 17. Use of global variables

    CREATE VARIABLE global_var_count INTEGER default 0;

    CREATE PROCEDURE project_count (IN var_respemp CHAR(6))BEGIN

    SELECT COUNT(*)INTO global_var_countFROM projectWHERE respemp = var_respemp;

    END

    CREATE PROCEDURE PROJECT_STATUS (IN p_respemp CHAR(6),OUTp_new_status CHAR(20))BEGIN

    CALL project_count(p_respemp);IF global_var_count > 2

    THENSET p_new_status = 'Maximum projects' ;

    ELSESET p_new_status = 'Available';

    END IF;END

    Section 5. Testing and deploying stored procedures

    DB2 supports the command line processor (CLP), which is an interface to deploy(build) and test (execute) stored procedures.

    The user building the stored procedure should satisfy the following requirements:

    Must have the privileges required to execute the CREATE PROCEDUREstatement

    Must have the privileges to execute all SQL statements in the storedprocedure

    All database objects (example, tables, views, functions, other procedures)

    that are referenced in this SQL procedure should exist in the database

    A successful database connection must be established from the CLP (thiscan be achieved by using the following db2 command : db2 connectto sample user userid using password )

    Each statement in an SQL procedure requires a statement terminator. The default is

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 17 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    18/24

    semicolon (;). You need to select an alternative termination character to be able tocreate an SQL procedure in a script for the CLP to know where your SQL procedureis terminated. Most commonly used termination characters are the "at" (@) andexclamation (!) characters.

    So now write a script that contains a simple SQL procedure and put the "@"termination character at the end:

    Listing 18. Simple SQL procedure with @ termintor at end

    CREATE PROCEDURE NUMBER_OF_ORDERS ( in_status varchar(10),in_date DATE,

    out num_of_order int)

    -------------------------------------------------------------------------- SQL Procedure------------------------------------------------------------------------P1: BEGIN

    declare v_number INTEGER DEFAULT 0;

    SELECT count(poid)INTO v_number

    FROM PURCHASEORDERwhere ucase(status) = ucase(in_status)

    and orderdate < in_date;

    SET num_of_order = v_number;

    END P1 @

    This script is saved as file myscript.db2. To build the stored procedurenumber_of_ordersfrom the DB2 CLP, you need to execute the following command:

    db2 -td@ -vf myscript.db2

    The general syntax for this CLP command is as follows:

    db2 -td -vf

    Note that the option -td indicates that the CLP terminator default is to be reset withthe corresponding terminating character. The -vf option indicates that the CLP'soptional verbose (-v) option is to be used, which causes each SQL statement orcommand in the script to be displayed on the screen as it is executed, along withany output that results from its execution. The -f option indicates that the target ofthe command is a file.

    Now it's time to execute (or test) this stored procedure from the CLP. To do that youneed to run the following command:

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 18 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    19/24

    db2 call number_of_orders('Shipped',current date, ?)

    Figure 3. Testing procedure from CLP

    Please note that you need to put a value for each input parameter and place a "?"(question mark) for each output parameter.

    But how would you know that the return value of 5 is correct? As this storedprocedure is simple and only has one SQL statement, you can execute thisstatement from the CLP by putting input parameters directly into the WHERE clauseas Listing 19 illustrates:

    Listing 19. SQL statement from procedure

    SELECT count(poid)FROM PURCHASEORDER

    WHERE ucase(status) = 'SHIPPED'AND orderdate < CURRENT DATE;

    Figure 4. Running this SQL Query from CLP

    As you can see, you get the same result. With more complex stored proceduretesting it could be a more time consuming task. You can use the IBM Data Studiotool to help you debug stored procedures.

    ibm.com/developerWorks developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 19 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    20/24

    Section 6. Securing SQL procedures

    Authorizations

    There are basically two types of authorization that needs to be considered for SQLprocedures:

    The stored procedure definer is the user who actually creates the storedprocedure.

    The stored procedure invoker is the user who invokes or calls the storedprocedure.

    In order to create an SQL procedure, the userid performing the task needs to haveBINDADD authority on the database and either IMPLICIT_SCHEMA on thedatabase (if the schema for the stored procedure does not already exist), orCREATE_IN on the schema (if the schema for the stored procedure does alreadyexist). They would also need to have all the necessary privileges to perform the SQLthat is defined in the stored procedure body.

    In order to invoke or call an SQL procedure, the userid performing the task needs tohave EXECUTE privilege on the stored procedure.

    The userid who created the SQL procedure implicitly gets EXECUTE privilege and

    the GRANT EXECUTE privilege. Either DBADM or SYSADM authority also allows auser to create or invoke an SQL procedure. It is generally recommended that adatabase administrator (DBA) is the one who creates the stored procedure for anapplication developer who may need to be able to invoke it.

    SQL access levels in SQL procedures

    There are four SQL access levels used for SQL statements that can control whattype of SQL statements the SQL procedure can define. They are used to provideinformation to the database manager so that the statement can be executed safely

    by the database manager.

    The SQL access levels that can be used are:

    NO SQL: no SQL statement can exist in the stored procedure

    CONTAINS SQL: no SQL statement can modify or read data in the storedprocedure

    developerWorks ibm.com/developerWorks

    DB2 SQL procedures Trademarks Copyright IBM Corporation 2008. All rights reserved. Page 20 of 24

    http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/ibm/trademarks/
  • 8/2/2019 735DB2Procedures

    21/24

    READS SQL: no SQL statement can modify data in the stored procedure

    MODIFIES SQL: SQL statements can both modify or read data in thestored procedure

    The default setting for SQL procedures is MODIFIES SQL.

    The SQL access level can also determine what kind of stored procedure can beinvoked from within that stored procedure. A stored procedure cannot call anotherstored procedure that is set with a higher SQL data access level. As an example, astored procedure defined with CONTAINS SQL can invoke a stored procedure thatis defined with either CONTAINS SQL or NO SQL. That same stored procedurecannot invoke another stored procedure that is defined with READS SQL DATA orMODIFIES SQL.

    The SQL access level can be specified during the CREATE PROCEDURE

    statement.

    Encrypting SQL procedures

    Moving SQL procedures from one server to another server is a common task. Forexample, a vendor may want to package up their SQL procedure and send thatpackage to their client. If the vendor wants to hide or encrypt the stored procedurecontents from their client, they can do that via the PUT ROUTINE and GETROUTINE commands.

    GET ROUTINE is a DB2 command that extracts an SQL procedure from thedatabase and converts it into a SAR (SQL Archive) file, which can then be sent tothe client.

    Listing 20. GET ROUTINE command syntax

    >>-GETROUTINE--INTO--file_name--FROM--+----------+------------->

    '-SPECIFIC-'

    >----PROCEDURE----routine_name--+-----------+------------------>>-PUTROUTINE--FROM--file-name--------------------------------->

    >--+-------------------------------------+--------------------->