Basic Stored Procedure
Basic Stored Procedure
Basic Stored Procedure
Version: 0.1
Creation date: 2005/05/17
Modified date:
Author: João Miguel Lopes
Teradata Series
Stored Procedures
0 INITIAL CONSIDERATIONS
This document describes the basics techniques, structure, syntax and semantics for stored
procedure development in Teradata DBMS environment.
Target readers for this document are analysts who are giving the first few steps in
developing or modelling solutions for Terad ata database environments. Previous
knowledge of Oracle database architecture/PL -SQL syntax is helpful but not necessary.
The examples provided for illustration purposes were developed against a demo version of
V2R5 (limited to 1 Gb) on a single 1.6 Mhz Intel Centrino processor machine, equipped
with 1Gb of RAM and an IDE hard drive, running Microsoft Windows XP Professional
Service Pack 2 as operating system. Therefore, all explain plans presented for select SQL
statements may differ if executed against different database versions and/or in different
hardware contexts.
1 INTRODUCTION
By definition, stored procedures are written in SQL and consist of a set of control and
condition handling statements that make SQL a computationally complete programming
language. This type of objects is also known as Persistent Stored Modules in the ANSI
SQL-99 standard (from which Teradata stored procedure facilities are a subset and
conform for semantics). They provide a procedural interface to the Teradata d atabase
engine and many of the same benefits as embedded SQL.
In this document we will approach the basic aspects of stored procedures like its structure
and most common techniques for development (dynamic SQL and recursion ) and with the
intent to provide some knowledge of how Teradata SQL differs from Oracle’s PL/SQL.
Target Pricing’s 1 stored procedures are used as example for comparison between Teradata
and Oracle SQL.
Teradata does not have the concept of objects like “package” and “function”,
implementing only the stored procedure object. Therefore, when migrating from
Oracle to Teradata all packages and functions must be c onverted to stored
procedures.
1
The Target Pricing version considered in this document is 1.0
TERADATA S ERIES Stored Procedures – The Basics Page 3/15
Teradata Series
Stored Procedures
2 STRUCTURE
Typically a stored procedure is composed by 2 four distinct parts. The following diagram
depicts those areas by the correct order.
Declaration Area
(Local variables, cursor declarations …)
END;
Note that, in Oracle, stored procedures have a similar structure . The only difference is that
the condition handling area is located below the control and SQL area. This does not mean
that stored procedures as a whole are similar between these two DMBSs … SQL code is
quite different as we will have the opportunity to see in the next f ew sections.
Each stored procedure can have up to 256 parameters regardless of its data type (all data
types supported by Teradata can be used for stored procedure parameters ).
Unlike Oracle, param eters can’t be defined with a default value. To workaround this
limitation one must declare a variable and initialize it with the desired default value.
2
If a stored procedure has one and only one SQL or control statement (including dynamic SQL) the declaration and
handling statements are dispensable.
TERADATA S ERIES Stored Procedures – The Basics Page 4/15
Teradata Series
Stored Procedures
Stored procedure parameters and their attributes are stored in the ‘DBC.TVFields’ table of
the data dictionary.
Example
The declaration area holds variable declaration and cursor definition statements. All
variables are private 3 to the stored procedure and can only be referenced inside the
procedure body.
Syntax
§ Variable declaration
§ Cursor declaration
Please note that all ‘DECLARE CURSOR’ statements must be specified after local variable
declarations and before any condition handler declarations.
Examples
§ Variable declaration
3
the concept of global variables, like those defined in package headers in Oracle does not natively exists in Teradata.
TERADATA S ERIES Stored Procedures – The Basics Page 5/15
Teradata Series
Stored Procedures
§ Cursor declaration
For more information about cursors please refer to “ Teradata Series – Cursors”.
The condition and control statement handling area is where one defines how to the
procedure should handle runtime errors and/or ex ceptions.
The difference between the two types is that ‘CONTINUE’ passes control to the next
statement within the compound statement and ‘EXIT’ passes control to the next statement
in the stored procedure outside the compound statement that contains the handler.
Unlike Oracle, Teradata has only three types of generic condition handlers:
§ SQLEXCEPTION
§ SQLWARNING
§ NOT FOUND
Other forms of condition handling are called SQLSTATE -based and must be explicitly
declared in the handling declaration statement.
Best Practise!
Handling conditions (especially SQLWARNING and SQLEXCEPTION) should
always be defined to ensure Enabler’s policy regarding defensive programming)
Syntax
Examples
For more information about condition handling please refer to “ Teradata Series – Condition
and Control Statement Handling”.
The procedure body - set of statements constituting the main tas ks of the stored
procedure - can be a single control statement or SQL statement, or a BEGIN … END
compound statement (sometimes called a block) which can also be nested. In other words,
this is the place where the real action takes place! In the next few sections we will
describe some of the most relevant components that are a part of the procedure body.
2.4.1 Labels
Examples
BEGIN
DECLARE CONTINUE HANDLER
FOR SQLEXCEPTION
set o_ck=-1;
select currency_key
into :o_ck
from ss_comp_pz_prices f
where f.pz_key=:p_pz_key
and f.sku_key=:p_sku_key
and f.comp_store_key=:p_vip_key;
END;
The procedure above receives three parameters and with them determines and returns the
corresponding currency surrogate key.
Dynamic SQL is a method of invoking an SQL statement (whose request text can vary
from execution to execution) by compiling and performing it at runtime from within a
stored procedure. One may invoke DDL, DML or DCL statements, with some exceptions, as
dynamic SQL in a stored procedure.
As in Oracle, dynamic SQL statements are not validated at compile time. Th e validation is
done only during execution of the stored procedure.
Syntax
Example
(...)
BEGIN
DECLARE sales_columns VARCHAR(128) DEFAULT '(item INTEGER,price DECIMAL(8,2),sold INTEGER)';
CALL DBC.SysExecSQL('CREATE TABLE ' || my_database ||'.' || my_table || my_columns) ;
END;
(...)
Please note that dynamic SQL syntax in stored procedure context is different from
embedded SQL (the expression embedded SQL refers to SQL statements performed or
declared from within a client application ). While in stored procedure one must use the
‘CALL DBC.SysExecSQL’ statement to order the execution of a query string, in embedded
SQL applications this is done with the EXECUTE IMMEDIATE statement. Please refer to
Teradata’s Documentation for details on developing embedd ed SQL applications.
A stored procedure can be recursive, referencing itself directly or indirectly. That is, the
stored procedure body can contain a CALL statement invoking the procedure being
defined. Such CALL statements c an also be nested. Please note that, w hen creating the
stored procedure if it directly references or invokes itself, the procedure is created with an
SPL compilation warning (not an error) because the referenced object (the procedure)
does not exist. This behaviour of a self-referencing stored procedure is different from the
general norm, where any reference to a missing object results in a compilation error (not
warning) and the stored procedure is not created. No specific limit exists on the level of
recursion, but the stored procedure nesting limit of 15 applies. The limit is further reduced,
if there are any open cursors.
Recursion types:
Single
We call simple to one side recursion (the procedures calls itself) .
SProc A
Mutual
You can also create mutually recursive stored procedures, that is, procedures invoking
each other in a stored procedure body. This is an indirect recursion.
SProc A SProc B
Chain
You can extend the mutual recursion process to have a recursion chain through multiple
procedures (A calls B, B calls C, and C calls A).
SProc A SProc B
SProc C
Examples
First, and to avoid compilation errors, one must create an empty stored procedure.
Now that the database object db1.Sp1 exists, we may create a second stored procedure
that will invoke db1.Sp1:
No errors found. Now just replace db1.Sp1 with the intended set of instructions:
5 PRIVILEGES
Syntax
Examples:
§ This example shows how to grant all privileges except drop on a stored
procedure to a specific user .
§ This example removes all privileges given above except the execute procedure.
As previously stated, Teradata doesn’t implement the concept of packages or functions like
Oracle. But, it does implement a type of object that is unavailable in Oracle: Macros. This
document does not provide extensive information about them but it is useful to enforce
the difference between this type of object and stored procedures.
Macros database objects are SQL statements that the server stores and executes by
performing a single statement. Yo u automatically get a multi statement request without
coding it if you write multiple SQL statements within a macro because macros are always
performed as a single request. The macro code can also specify parameters that are
replaced by data each time the macro is performed. The most common way of substituting
for the parameters is to specify a USING. Macros are usually more efficient for repetitive
queries than single DML statements. Unlike stored procedures, macros are not designed to
return parameters to the requestor: they return only the answer set for the SQL
statements they contain .
The following table highlights the major differences between stored procedures and
macros:
§ Be aware for parameter naming conventions. Teradata forces the CALL statement to
enumerate stored procedure parameters with the exa ct same name as defined in the
create procedure clause. For instance, if a stored procedure named SP1 has a INOUT
parameter named P1 then, when calling this procedure for execution we must type:
‘CALL SP1(P1)’. The attempt to use any other parameter name w ill fail.