Vous êtes sur la page 1sur 7

1.

Stored procedure and its purpose ans advantages: DB2 Stored Procedures and the Mainframe Stored Procedures are a very powerful database feature that can often be employed to great benefit. However, in the context of an application running entirely on the mainframe, using stored procedures can bring you no benefit and sometimes can even be detrimental to your application. Lets analyze why this can be... First, let's review some of the benefits of stored procedures. Reducing network traffic and client code complexity in a client/server environment - if the application logic requires processing large result sets, and that logic can be encapsulated in a stored procedure, we can reduce the amount of data going back and forth between the client and the server. Centralizing common business rules for accessing and manipulating the data. Providing a standard API(SQL) and an application server type environment (transactionality, work load managed address spaces) for all clients on and off the host.

Now lets review some details about how stored procedures are implemented in DB2. In DB2-land, stored procedures can be of two types, fenced and non-fenced. Non-fenced stored procedures run in a DB2 address space. Fenced stored procedures run in separate address spaces from DB2. If a nonfenced stored procedure crashes badly, it can possibly bring down DB2. For this reason, the mainframe version of DB2 allows only fenced stored procedures. A fenced stored procedure is essentially a standalone program that is invoked through SQL. There are various restrictions on what this program can do, but overall, the program can pretty much do anything it wants: read files, send and receive MQ messages, and of course execute SQL. Here is an interaction diagram of the address spaces involved and the flow of information through them.

Notice that the application program interacts with the stored procedure by first going through the DB2 Master address space. It's a bit of a ping-pong game, trying to follow the flow of information. Let's compare this to the stadard way that a local program interacts with DB2.

As you can see, in this case the interactions are much simpler, avoiding the cross address space memory transfers.

What Is a Stored Procedure? If a procedure is encapsulated logic that can be invoked from within your application, then a stored procedure is simply a procedure that is stored on the database server. Usually written in SQL, the stored procedure benefits from the power and proximity of the database from which it is managed. If you've used a database at all in your applications, then you've most likely coded in SQL at some point. To turn it into a stored procedure, you can include it within a CREATE PROCEDURE statement. Technically, it would be a stored procedure and could thus be invoked from external applications. But the true power of the stored procedure comes from its control syntax and ability to process multiple statements. In other words, while you would rarely use a stored procedure for a single SELECT statement, you could add INSERT, UPDATE, and DELETE statements, all controlled withIF/ELSE logic, for example. Just about any database manipulation you're doing with your app code can be done within a stored procedure instead, with all of its inherent benefits. When Do I Use Stored Procedures? Coders might argue that you never really need a stored procedure. All of your database calls can be done programmatically. That's true, but somewhat limiting. Stored procedures can do a lot of things for you that even the most elegant code cannot. Chief among these, stored procedures save processor time by allowing you to offload database calls to the database server itself. Most databases load the compiled procedures into memory the first time they're called, or even before, dramatically reducing overhead when you're doing the same essential process multiple times (such looping operations are very common in database manipulation). Stored procedures offer you many other benefits, as well. They allow you to encapsulate code. In other words, the database operation appears once, in the stored procedure, not multiple times throughout your application source. This improves debugging as well as maintainability. Changes to the database schema affect your source code in only one place, the stored procedure. Any schema changes then become a DBA task rather than a wholesale code revision. Since the stored procedures reside on the server, you can set tighter security restrictions on the client space, saving more trusted database permissions for the well-protected stored procedures themselves. Since stored procedures are compiled and stored outside the application, they can use more sensitive variables within the SQL syntax, such as passwords or personal data, that you would avoid using in scripts or remote calls. Using stored procedures greatly reduces network traffic.

As a further illustration of this last point, suppose you want to update a customer record but you're not sure if the record even exists. One way is (a) to SELECT the record to see if the customer exists, (b) to UPDATE the record if it does, and (c) to INSERT a new record if it does not. If you just put a series of SQL statements in your client code, each line is executed by sending a message over the network to the server, usually getting a response in return. But a stored procedure resides on the server. When called from the client application, it executes on the server and only has to respond when returning the final result set to the client, saving lots of back-and-forth traffic.

When Would I Not Use Stored Procedures? Whole discussion boards have been devoted to the pro/con debate on stored procedures. But when it comes down to it, you have only a few occasions when it might not be possible or prudent to use them. You don't have the database permissions to create them. Or a cooperative DBA. You're only using a few SELECT statements in your application and can't really benefit from the performance and organizational boosts offered by stored procedures (though you might still profit from the other gifts of the stored procedure). Your organization is undergoing a major code migration and wants to avoid encapsulating your source in external procedures. However, this is debatable as well since you may actually benefit from the stability of SQL syntax.

What's Special About DB2's Stored Procedures? DB2 expands on the definition of a stored procedure by allowing you to code them in just about any language you may need. DB2 gives you two different kinds of stored procedures: a SQL procedure, and an external procedure. In DB2, a stored procedure is a database object that encapsulates control-flow logic, a mini application really, that runs in a "stored procedure address space." Going back to the idea that a stored procedure is simply a chunk of compiled code, DB2 stored procedures can be written in your language of choice, compiled, then referenced with SQL syntax. The major difference between a SQL procedure and an external procedure is that SQL procedures are, obviously, written in SQL. This means that the logic for the procedure is defined within the SQL procedure body itself. By contrast, external procedures identify, load, and run a unit of code written in an entirely different language. Early stored procedures were all essentially external, generally written in C. Nowadays, when we talk about stored procedures, most people think of SQL procedures which are written in easy to implement high-level SQL syntax. But DB2's external procedures provide a handy option for the codernauts and those wanting to implement more complex logic than SQL can support, using languages such as Visual Basic .NET, C, C++, C#, COBOL, Java, or REXX. If you're using the DB2 Development Center tooling, then once the procedure is created, the following chunk of code is automatically generated by DB2. It creates a handle for the above procedure in the database. When you call this procedure from your application, the above code is then looked up, identified, found, and run by DB2. CREATE PROCEDURE ADMINISTRATOR.UPDATE_SAL ( IN empNum CHAR(6), IN rating SmallInt ) SPECIFIC ADMINISTRATOR.UPDATE_SAL DYNAMIC RESULT SETS 0 NOT DETERMINISTIC LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME 'MyJavaClass.UpdateSal' FENCED THREADSAFE For comparison, here is the same basic operation written as a SQL procedure. You'll see that the UPDATE statement remains the same, but control flow operations are now managed by SQL syntax included in the CREATE PROCEDURE statement itself. CREATE PROCEDURE ADMINISTRATOR.UPDATE_SAL (IN empNum CHAR(6), IN rating SMALLINT) LANGUAGE SQL BEGIN

IF rating = 1 THEN UPDATE employee SET salary = salary * 1.10, bonus = 1500 WHERE empno = empNum; ELSE UPDATE employee SET salary = salary * 1.05, bonus = 1000 WHERE empno = empNum; END IF; END Once your stored procedure has been successfully created and you have the privileges to invoke it (you will have these by default if you are the creator) then the procedure can be called. As you can see, SQL procedures give you an easy-to-use syntax for handling multiple statements and control flow within the procedure itself. External procedures give you the power and flexibility of using your language of choice, opening up all new possibilities for straight coders and DBAs alike. DB2 views A view is an alternative way of representing data that exists in one or more tables. A view can include all or some of the columns from one or more base tables. A view is a named specification of a result table. Conceptually, creating a view is somewhat like using binoculars. You might look through binoculars to see an entire landscape or to look at a specific image within the landscape, such as a tree. You can create a view that: Combines data from different base tables Is based on other views or on a combination of views and tables Omits certain data, thereby shielding some table data from users

In fact, these are common underlying reasons to use a view. Combining information from base tables and views simplifies retrieving data for a user, and limiting the data that a user can see is useful for security. You can use views for a number of different purposes. A view can: Control access to a table Make data easier to use Simplify authorization by granting access to a view without granting access to the table Show only portions of data in the table Show summary data for a given table Combine two or more tables in meaningful ways Show only the selected rows that are pertinent to the process that uses the view

To define a view, you use the CREATE VIEW statement and assign a name (up to 128 characters in length) to the view. Specifying the view in other SQL statements is effectively like running an SQL SELECT statement. At any time, the view consists of the rows that would result from the SELECT statement that it contains. You can think of a view as having columns and rows just like the base table on which the view is defined.

Example

Example 1: The following figure shows a view of the EMP table that omits sensitive employee information and renames some of the columns. Figure 1. A view of the EMP table

Figure note: The EMPINFO view represents a table that includes columns named EMPLOYEE, FIRSTNAME, LASTNAME, TEAM, and JOBTITLE. The data in the view comes from the columns EMPNO, FIRSTNME, LASTNAME, DEPT, and JOB of the EMP table. Example 2: The following CREATE VIEW statement defines the EMPINFO view that is shown in the preceding figure: CREATE VIEW EMPINFO (EMPLOYEE, FIRSTNAME, LASTNAME, TEAM, JOBTITLE) AS SELECT EMPNO, FIRSTNME, LASTNAME, DEPT, JOB FROM EMP; When you define a view, DB2 stores the definition of the view in the DB2 catalog. However, DB2 does not store any data for the view itself, because the data exists in the base table or tables. Example 3: You can narrow the scope of the EMPINFO view by limiting the content to a subset of rows and columns that includes departments A00 and C01 only: CREATE VIEW EMPINFO (EMPLOYEE, FIRSTNAME, LASTNAME, TEAM, JOBTITLE) AS SELECT EMPNO, FIRSTNME, LASTNAME, DEPT, JOB WHERE DEPT = 'AOO' OR DEPT = 'C01' FROM EMP;

In general, a view inherits the attributes of the object from which it is derived. Columns that are added to the tables after the view is defined on those tables do not appear in the view. Restriction: You cannot create an index for a view. In addition, you cannot create any form of a key or a constraint (referential or otherwise) on a view. Such indexes, keys, or constraints must be built on the tables that the view references. To retrieve or access information from a view, you use views like you use base tables. You can use a SELECT statement to show the information from the view. The SELECT statement can name other views and tables, and it can use the WHERE, GROUP BY, and HAVING clauses. It cannot use the ORDER BY clause or name a host variable.

Whether a view can be used in an insert, update, or delete operation depends on its definition. For example, if a view includes a foreign key of its base table, INSERT and UPDATE operations that use the view are subject to the same referential constraint as the base table. Likewise, if the base table of a view is a parent table, DELETE operations that use the view are subject to the same rules as DELETE operations on the base table. Read-onlyviews cannot be used for insert, update, and delete operations. Advantages of views: Views can represent a subset of the data contained in a table Views can join and simplify multiple tables into a single virtual table Views can act as aggregated tables, where the database engine aggregates data (sum, average etc.) and presents the calculated results as part of the data Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table Views take very little space to store; the database contains only the definition of a view, not a copy of all the data it presents Depending on the SQL engine used, views can provide extra security Views can limit the degree of exposure of a table or tables to the outer world

List of db2 functions: Built-In Functions Overview A function is an operation denoted by a function name followed by a pair of parentheses enclosing zero or more arguments. Along with many SQL statements, DB2 also includes a large set of built-in functions capable of returning a variety of data values or converting values from one data type to another. DB2 includes the following basic types of built-in functions: Aggregate (Column): These functions affect all values in a specified column. Scalar: These functions affect a single value in a table or view. Row Functions: These functions return a single row to the SQL statement that references them. Table Functions: These functions return multiple rows to the SQL statement that references them.

DB2 also allows the creation of User-Defined functions. Click here for more information. Aggregate (Column) Functions A column function accepts a collection of like values as its argument. It returns a single value (possibly null) and can be specified in an SQL statement wherever an expression can be used. DB2 UDB provides the following column functions (click on each function for more information): ARRAY_AGG AVG COVARIANCE GROUPING STDDEV SUM VARIANCE

CORRELATION MAX

COUNT COUNT_BIG

MIN

XMLAGG

Regression Functions XMLGROUP

Scalar Functions Scalar functions accept individual values as arguments. These values can be of different data types and can have different meanings. A scalar function returns a single value (possibly null) and can be specified in an SQL statement wherever an expression can be used. The following table shows some of the more common scalar functions: Function ABS(Value) COALESCE(Expression, Expression,) LENGTH('CharacterString') LCASE('CharacterString') or LOWER('CharacterString') UCASE('CharacterString') or UPPER('CharacterString') 'CharacterString'). MONTH('DateValue') DAY('DateValue') YEAR('DateValue') Row and Table Functions Row and table functions are special functions because they return one or more rows to the SQL statement that reference them and can only be specified in the FROM clause of a SELECT statement. Such functions are typically used to work with data that does not reside in a DB2 UDB database and/or to convert such data into a format that resembles that of a DB2 table. (The built-in function SNAPSHOT_TABLE is an example of a table function.) Purpose Returns the absolute value of the value specified. Returns the first expression found in the list provided that is not null (for example, COALESCE(EMPID, 0) returns the value for EMPID unless that value is null, in which case the value 0 will be returned instead). Returns the number of bytes found in the character string value specified. Returns a character string in which all of the characters in the character string value specified are converted to lowercase characters. Returns a character string in which all of the characters in the character string value specified are converted to uppercase characters. Returns a date value from a numeric value or string. Returns the month portion of the date value specified. Returns the day portion of the date value specified. Returns the year portion of the date value specified.

Vous aimerez peut-être aussi