SQLSP
SQLSP
All rights reserved. No part of this manual may be reproduced, stored in a retrieval system, or transmitted in any
form, without the prior written permission of the manufacturer.
For a description of updated functions that do not appear in this manual, read the file named README.TXT
after installing the CASEMaker DBMaker software.
Trademarks
CASEMaker, the CASEMaker logo, and DBMaker are registered trademarks of CASEMaker Inc. Microsoft, MS-
DOS, Windows, and Windows NT are registered trademarks of Microsoft Corp. UNIX is a registered trademark
of The Open Group. ANSI is a registered trademark of American National Standards Institute, Inc.
Other product names mentioned herein may be trademarks of their respective holders and are mentioned only
form information purposes. SQL is an industry language and is not the property of any company or group of
companies, or of any organization or group of organizations.
Notices
The software described in this manual is covered by the license agreement supplied with the software.
Contact your dealer for warranty details. Your dealer makes no representations or warranties with respect to the
merchantability or fitness of this computer product for any particular purpose. Your dealer is not responsible for
any damage caused to this computer product by external forces including sudden shock, excess heat, cold, or
humidity, nor for any loss or damage caused by incorrect voltage or incompatible hardware and/or software.
Information in this manual has been carefully checked for reliability; however, no responsibility is assumed for
inaccuracies. This manual is subject to change without notice.
Contens
1 Introduction ..............................................1-1
1.1 Other Sources of Information ...................... 1-2
1.2 Technical Support ....................................... 1-3
1.3 Document Conventions ............................... 1-4
2 DBMaker Stored Procedure Overview ......2-1
2.1 What is a Stored Procedure ......................... 2-1
2.2 DBMaker Supported Stored Procedure
Languages ................................................... 2-2
ESQL/C Stored Procedure..................................................... 2-2
JAVA Stored Procedure ......................................................... 2-2
SQL Stored Procedure ........................................................... 2-3
3 SQL Stored Procedures ............................3-1
3.1 Advantages of SQL Stored Procedures ....... 3-2
Systems Run Faster ................................................................ 3-2
Reusable ................................................................................ 3-2
Persistent ............................................................................... 3-3
Easy to Migrate ..................................................................... 3-3
Easy to Upgrade .................................................................... 3-3
Other Advantages .................................................................. 3-3
1 Introduction
Welcome to the DBMaker SQL Stored Procedure User's Guide. DBMaker is a powerful
and flexible SQL Database Management System (DBMS) that supports an interactive
Structured Query Language (SQL), a Microsoft Open Database Connectivity (ODBC)
compatible interface, and Embedded SQL for C (ESQL/C). The unique open
architecture and native ODBC interface give you the freedom to build custom
applications using a wide variety of programming tools or to query databases using
existing ODBC-compliant applications.
This manual includes the basic operations of SQL stored procedure and provides
systematic instructions that guide you through the management of a database. The
User's Guide content is intended for designers and administers of DBMaker databases.
It will assist those unfamiliar with using DBMaker, but have some understanding of
The manual shows various commands and procedures used in maintaining a database
with SQL stored procedure. Although the manual is for DBMaker on Windows
environments, it can perform all functions on a UNIX platform. For clarity purposes,
portions of sample databases appear through out this manual.
Generally, all major RDBMS provide their own user interface for using SQL. For
example, DBMaker provides dmSQL/C. Users can input SQL syntax directly through
the tool to access and maintain their database.
DBMaker also comes with a variety of Java Tools. For more information on a
particular subject, refer to the Additional Resources section that follows and select the
appropriate manual.
For more information on DBMaker functions, refer to the JDBA Tool User's
Guide.
For more information on the DCI COBOL interface tool, refer to the DCI User's
Guide.
For more information on the SQL language used in dmSQL, refer to the SQL
Command and Function Reference.
For more information on the dmSQL, refer to the dmSQL User's Guide.
For more information on the native ODBC API and JDBC API, refer to the
ODBC Programmer's Guide and JDBC Programmer's Guide.
For more information on error and warning messages, refer to the Error and
Message Reference.
For more information on the ESQL/C programming, refer to the ESQL/C User's
Guide.
For more information on the Java stored procedure, refer to the JAVA stored
procedure Guide.
For most products, support is available beyond sixty days and may be purchased for
twenty percent of the retail price of the product. Please contact [email protected]
for details and prices.
CASEMaker support contact information, by post mail, phone, or email, for your area
is at: www.casemaker.com/support. We recommend searching the most current
database of FAQ's before contacting CASEMaker support staff.
Registration number
CONVENTION DESCRIPTION
Italics Italics indicate placeholders for information that must be
supplied, such as user and table names. The word in italics should
not be typed, but is replaced by the actual name. Italics also
introduce new words, and are occasionally used for emphasis in
text.
Boldface Boldface indicates filenames, database names, table names,
column names, user names, and other database schema objects. It
is also used to emphasize menu commands in procedural steps.
KEYWORDS All keywords used by the SQL language appear in uppercase when
used in normal paragraph text.
CONVENTION DESCRIPTION
SMALL CAPS Small capital letters indicate keys on the keyboard. A plus sign (+)
between two key names indicates to hold down the first key while
pressing the second. A comma (,) between two key names
indicates to release the first key before pressing the second key.
NOTE Contains important information.
Procedure Indicates that procedural steps or sequential items will follow.
Many tasks are described using this format to provide a logical
sequence of steps for the user to follow.
Example Examples are given to clarify descriptions, and commonly include
text, as it will appear on the screen. Other forms of this
convention include Prototype and Syntax.
Command Line Indicates text, as it should appear on a text-delimited screen. This
format is commonly used to show input and output for dmSQL
commands or the content in the dmconfig.ini file.
Table 1-1 Document Conventions
2 DBMaker Stored
Procedure Overview
We provide a general description of ESQL, Java stored procedure and SQL stored
procedure in this chapter.
Because stored procedures run in the DBMS itself, they can help to reduce latency in
applications. Rather than executing four or five SQL statements in your applications,
you just execute one stored procedure that does the operations for you on the server
side. Reducing the number of network trips alone can have a dramatic effect on
performance.
This book concentrates on the development of stored procedures written in the SQL
language.
DBMaker ESQL/C provides the convenience of entering SQL statements directly into
the C language source code. An ESQL stored procedure is an ESQL/C program.
Stored procedures can perform any function a C application can, including calling
other C functions and system calls. Therefore, a C compiler is required for writing
stored procedures. You can write C application programs that use ESQL commands to
access a DBMS. The DBMaker ESQL/C preprocessor prepares the application
program containing the SQL commands for the C compiler. The preprocessor then
converts the SQL commands to C statements, with C comments, to perform the
database operations.
For experienced ESQL developers, Java allows you to extend the functionality of
database applications. Java also allows you to reuse code and dramatically increase
productivity.
Each Java stored procedure is implemented as a Java method. When you call it, the
name of the procedure and the parameters you specify are sent over the JDBC
connection to the DBMS, which executes the procedure and returns the results back
over the connection.
For more information on Java stored procedure, refer to the Java Stored Procedure
Guide and select the appropriate sections.
Using ESQL and Java to create stored procedures is inefficient. Directly using SQL
statements to create a SQL stored procedure if much more efficient.
SQL stored procedures are stored procedures that are implemented with only SQL
statements. A SQL stored procedure is a set of SQL statements that is stored on the
server. Clients can refer to SQL stored procedures rather than repetitively executing
statements.
3 SQL Stored
Procedures
A SQL stored procedure is a special kind of user-defined function. Once the stored
procedure has been created, it is stored in executable format in the database as an
object, it can be used to create simple scripts for quickly querying transforming, and
updating data or for generating basic reports, for improving application performance,
for modularizing applications, and for improving overall database design, and database
security. This allows the database engine to bypass repeated SQL compilation and
optimization, increasing the performance of frequently repeated tasks. Stored
procedure is executed as a command in interactive SQL, or invoked in application
programs, trigger actions, or other store procedures.
Before deciding to implement a SQL stored procedure, it is important that you first
understand what SQL stored procedures are, how they are implemented. With that
knowledge you can learn more about SQL stored procedure from the following
concept topics so that you can make informed decisions about when and how to use
them in your database environment:
SQL stored procedures advantages
In the absence of a compiler, so SQL stored procedure is not same as program that
written by external language (such as ESQL/C) running so fast. However, the primary
method for enhancing speed is to reduce network traffic, if you need to deal with the
task is checking, recycling and multi-statement, but there is no user interactive
duplication tasks, you can use stored procedures to reduce server load. So that each
step to execute task, between the server and the client side is not have so much
information exchange.
Reusable
SQL stored procedure can cross platforms and support Win32/64 and Linux32/64
systems.
Whether you change the host language has no impact on the SQL stored procedures,
because it is the database logic rather than the application. Stored procedures can be
migrated, when you use the SQL language creating stored procedures, you know that
it can run on any platform supported by DBMaker, does not require adding operating
specific details, nor the need for implementation setting license in operating system for
procedure, or configuring different software packages for your computer, which is the
advantage of using SQL statement compared with Java and ESQL/C external
languages.
Persistent
If you write a complete procedure, such as indicates the check cancel operation in the
banking transaction processing. Then the person who wants to understand the checks
could find your program. It will be in the form of source code stored in the database,
which will make the process of data and processing data associated.
Easy to Migrate
DBMaker support the highly portable SQL 99 standard. Other DBMS also support
this standard, so the code written using other DBMS can easily migrate to DBMaker.
Easy to Upgrade
SQL Stored Procedure is same as the DBMaker ESQL data types, creation, execution
and delete, so that convenience of existing customers to upgrade, and the client
program does not require any changes.
Other Advantages
Because they do not use the extra C compiler, so it will not appear the problem that is
affected by the compiler, such as the installation path or the compiler unloading.
Easy to use, syntax simple, clear, structural strong. This feature will be introduced in
later in SQL Stored Procedure Syntax.
JDBA Tool
dmSQL
JDBA Tool
JDBA Tool is a cross-platform user-friendly graphical user interface (GUI) that helps
users to easily manage database objects in DBMaker, a powerful and flexible SQL
Database Management System. JDBA tool hides the complexity of the DBMS and
query language and provides an easy to understand and convenient to use interface.
You can perform database functions without having to learn SQL. JDBA Tool's
monitoring functions also provides statistical data and information on who is using
your database. Refer to the JDBA Tool Reference for more information about how to
use JDBA tool.
dmSQL
dmSQL is a command line tool, you can do many more things within the DBMaker
dmSQL tool that can assist you in developing SQL stored procedures, including:
querying, modifying, loading, and extracting table data, working with XML functions,
executing Java routines, and more. Refer to the dmSQL User's Guide for more
information about how to use dmSQL command line tool.
4 SQL Stored
Procedures Function
Can contain Stored Procedural Language statements and features which support
the implementation of control-flow logic around traditional static and dynamic
SQL statements.
Are easy to implement, because they use a simple high-level, strongly typed
language.
SQL Store procedures are more reliable than equivalent external procedures.
Allow you to return single result sets to the caller or to a client application.
Allow you to easily access the SQLSTATE and SQLCODE values as special
variables but not support assignment values to SQLSTATE and SQLCODE.
Support recursion.
Support control flow statement: IF, CASE, WHILE, LOOP, FOR, REPEAT,
GOTO, RETURN
SQL Stored procedures provide extensive support not limited to what is listed above.
When implemented according to best practices, they can play an essential role in
database architecture, database application design, and in database system
performance.
5 SQL Stored
Procedures Syntax
The SQL Stored Procedure Language (SQL SP) is accord with ANSI SQL99
language standard, it is a set of SQL statements that was introduced in SQL Command
and Function Reference to provide the procedural constructs necessary for
implementing control flow logic around traditional SQL queries and operations.
SQL Stored Procedure has a simple syntax that includes support for variables,
conditional statements, looping statements, transfer of control statements, error
management statements, and result set manipulation statements.
Above shows that SQL stored procedures can consist of one or more optionally atomic
compound statements (or blocks) and that these blocks can be nested or serially
introduced within a single SQL stored procedure. Within each of these atomic blocks
there is a prescribed order for the optional variable, condition, and handler
declarations. These must precede the introduction of procedural logic implemented
with SQL-control statements and other SQL statements and cursor declarations.
Cursors can be declared anywhere with the set of SQL statements contained in the
SQL stored procedure body.
LANGUAGE SQL
BEGIN
[stored_procedure_statement]
END;
<procedure_parameters> ::=
[IN | OUT | INPUT | OUTPUT] <parameter_name> <data_type>
Above syntax demonstrate the SQL stored procedure overall frame, a complete SQL
stored procedure must contain a block header and block end, block header is used to
describe name and its parameters of the SQL stored procedure, block end is only an
end sign, such as:
CREATE [OR REPLACE] PROCEDURE project_name.module_name.sp_name
[ arg_list ]
LANGUAGE SQL
BEGIN
----------------->Block header
[ declare_list ]
[ statement_list ]
-----------------> Block end
END;
Arg_list is a parameter list, input parameters and output parameters in the declare
process, and will not return parameter if it is NULL.
<Arg_list> ::=
[ Variable declarations ]
[ Condition declarations ]
[ Cursor declarations ]
[ Condition handler declarations ]
Parameters can be useful in SQL stored procedures when implementing logic that is
conditional on a particular input or set of input scalar values or when you need to
return one or more output scalar values but do not want to return a result set.
SQL stored procedure supports data types is: SMALLINT, INTEGER, BIGINT,
FLOAT, DOUBLE, DECIMAL, REAL,DATE, TIME, TIMESTAMP,
BINARY, CHAR, VARCHAR, NCHAR, NVARCHAR.
This clause is optional. SQL stored procedure is same as ordinary function that have
it's parameters to convey data, Main function can convey data to stored procedure by
adding 'in/input' after parameters. SQL stored procedure also can convey the disposed
date to main function by adding 'out/output' after parameters.
Example 1:The following SQL stored procedure named myparams illustrates the
use of IN/INPUT, and OUT/OUTPUT parameter modes.
CREATE PROCEDURE myparams (IN p1 INT, OUT p2 INT, OUT p3 INT)
LANGUAGE SQL
BEGIN
SET p2 = p1 + 1;
SET p3 = 2 * p1;
END;
The parameters of SQL stored procedure CRETB is ignored, its function is to create a
table named TB_1.
All the parameter types of SQL stored procedure INS is INPUT. Input parameter data
type in INS contains all the data type supported by SQL stored procedure. The
function as shown in above case is to insert input data into the existing INS table.
NOTE All the current row with "#" began in this manual example as a comment.
BEGIN
IF V1 = 'DROP TABLE' THEN
DROP TABLE TB_1;
SET WORNING ='NORMAL! TABLE TB_1 DROPED';
ELSEIF V1 = 'CREATE TABLE' THEN
CALL CRETB;
SET WORNING ='NORMAL! CREATE A NEW TABLE NAMED TB_1';
ELSE
SET WORNING = 'YOU INPUT WRONG PARAMETER!';
END IF;
END;
The SQL stored procedure DRPTB in the above case is not only have input
parameters, but also have output parameters. It determines the input parameters in the
process of body, if the input parameter is 'DROP TABLE', then the SQL stored
procedure executes the DROP TABLE command and sets the output parameters to
'NORMAL! TABLE TB_1 DROPED'. So it can control the output parameters based
on the input parameters.
This statement is used to declare local variables. To provide a default value for the
variable, include a default clause. The value can be specified as an expression, it need
not be a constant if the default clause is missing. The initial value is null.
The scope of a local variable is within the begin…end block where it is declared. The
variable can be referred to in blocks nested within the declaring block except those
blocks that declare a variable with the same name.
A cursor can be viewed as a pointer to one row in a set of rows and can only reference
one row at a time, but can move to other rows of the result set as needed.
3. Fetch the data into local variables as needed from the cursor, one row at a time
To work with cursors you must use the following SQL statements:
DECLARE CURSOR
FETCH
CLOSE
cursor_name
Specifies the name of the cursor created when the source program is run. The name
must not be the same as the name of another cursor declared in the source program.
The cursor must be opened before use.
[NO] SCROLL
If the SCROLL clause isn't used or only the NO SCROLL clause is used in the
definition of the DECLARE CURSOR statement, the FECTCH statement will not
execute any operation expect the NEXT behavior. Contrarily, if the SCROLL clause is
used, then all behavior of the FETCH statement can be used. Default value is non-
scrollable cursor.
WITH RETURN
Within a SQL stored procedure, cursors declared using the WITH RETURN clause
that are still open when the SQL stored procedure ends, define the result sets from the
SQL stored procedure. All other open cursors in a SQL stored procedure are closed
when the SQL stored procedure ends. Within an external stored procedure (one not
defined using LANGUAGE SQL), the default for all cursors is WITH RETURN TO
CALL. Therefore, all cursors that are open when the procedure ends will be
considered result sets.
Select_statement
Identifies the SELECT statement of the cursor. The select-statement must not include
parameter markers, but can include references to host variables. The declarations of
the host variables must precede the DECLARE CURSOR statement in the source
program.
call
Specifies that the cursor can return a result set to the caller. For example, if the caller is
another stored procedure, the result set is returned to that stored procedure. If the
caller is a client application, the result set is returned to the client application.
OPEN cur;
FETCH cur INTO bd;
CLOSE cur;
END;
Example 5: The following example demonstrates the basic usage of a read-only cursor
within a SQL stored procedure:
CREATE PROCEDURE sum_salaries(OUT sum INTEGER)
LANGUAGE SQL
BEGIN
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLCODE = 0)
DO
SET p_sum = p_sum + p_sal;
FETCH FROM c INTO p_sal;
END WHILE;
CLOSE c;
SET sum = p_sum;
END;
CREATE PROCEDURE sum_salaries(OUT sum INTEGER)
LANGUAGE SQL
BEGIN
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLCODE = 0)
DO
SET p_sum = p_sum + p_sal;
The FETCH statement positions a cursor on the next row of its result table and
assigns the values of that row to host variables. Although an interactive SQL facility
might provide an interface that gives the appearance of interactive execution, this
statement can only be embedded within an application program. It is an executable
statement that cannot be dynamically prepared.
cursor-name
Identifies the cursor to be used in the fetch operation. The cursor-name must identify
a declared cursor, as explained in "DECLARE CURSOR". The DECLARE
CURSOR statement must precede the FETCH statement in the source program.
When the FETCH statement is executed, the cursor must be in the open state.
NEXT
Returns the next row within the results set. NEXT is the default cursor fetch.
LAST
The LAST command moves the cursor to the last row within the result set and returns
the last row.
FIRST
PRIOR
The PRIOR command returns the previous row within the results set.
ABSOLUTE n
Returns the n row from the first row within the result set
RELATIVE n
Returns the n row from the current row within the result set
INTO fetch_target_arg
Identifies one or more variables that must be described in accordance with the rules
for declaring variables. The first value in the result row is assigned to the first variable
in the list, the second value to the second variable, and so on.
Example 1: fetch
CREATE PROCEDURE t43_sql(i SMALLINT, OUT ts1 TIMESTAMP)
LANGUAGE SQL
BEGIN
DECLARE cur CURSOR FOR select TS from t2 where n = i;
OPEN cur;
FETCH cur INTO ts1;
CLOSE cur;
END;
Certain conditions may require specific handling. These conditions can relate to
errors, as well as to general flow control inside a routine.
Example :
DECLARE con1 CONDITION FOR SQLSTATE '23000';
DECLARE con2 CONDITION FOR SQLSTATE VALUE '23001';
The user can redefine the DECLARE HANDLER statement, then previous actions
defined by the DECLARE HANDLER statement will be re-set.Syntax: DECLARE
HANDLE statement syntax
<handler declaration> ::=
DECLARE <handler type> HANDLER FOR <condition value list> <handler
action>
<handler type> ::=
CONTINUE
| EXIT
<handler action> ::= <SQL procedure statement>
<condition value list> ::= <condition value> [ { <comma> <condition
value> }... ]
<condition value> ::=
<sqlstate value>
| <condition name>
| SQLEXCEPTION
| SQLWARNING
| NOT FOUND
Example 1:
create procedure sphdler
language sql
begin
declare continue handler for sqlexception;
drop table tb_1;
declare exit handler for sqlexception;
drop table tb_1;
end
The SET Variable statement assigns values to local variables, output parameters, or
new transition variables. It is under transaction control. SET assignment statements
accept simple expressions and complex expressions.
NOTE For the string data type variable assignment, assignment length is less than 1024
bytes.
Example 1:The following example demonstrates various methods for assigning and
retrieving variable values
CREATE PROCEDURE proc_vars()
LANGUAGE SQL
BEGIN
DECLARE v_rcount INTEGER;
DECLARE v_max DECIMAL (9,2);
DECLARE v_adate, v_another DATE;
DECLARE v_total INTEGER DEFAULT 0; # (1)
SET v_total = v_total + 1; # (2)
DECLARE CUR CURSOR FOR SELECT * FROM TB_1; # (3)
END;
When declaring a variable, you can specify a default value using the DEFAULT clause
as in line (1). Line (2) shows that a SET statement can be used to assign a single
variable value. Line (3) shows you can specify a value using the CURSOR FOR
SELECT FROM.
NOTE DECLARE must be in front of the SET definition, or the preprocessor compile
error.
In the SET assignment statement, for values exceeding the range of double and integer
data type, which can be accepted if the assigned variables are corresponding data types,
or will be truncated according to double and integer values range.
DECLARE d1, d2 DECIMAL(20, 10);
DECLARE b1, b2 BIGINT;
SET d1 = 1234.43534534531; # exceeding the double data type range
SET d2 = 1234.43534534532;
The comparison result of the above SET equation is d1 less than d2, b1 less than b2.
However such as the following IF statement, d1 and d2, b1 and b2 are equal, because
the exceeding rang parts were truncated.
IF 1234.43534534531 = 1234.43534534532 THEN …… #as double data type
Intercepted
IF 1234454654645645651 = 1234454654645645652 THEN …… #as integer data type
Intercepted
Simple expression
Example 1:
CREATE PROCEDURE SETTS(out rc1 int, out rc2 int, out rc3 char(10))
LANGUAGE SQL
BEGIN
DECLARE d1 INT DEFAULT 2;
DECLARE d2,d3 INT DEFAULT 2;
DECLARE c1,c2 char(10) DEFAULT '12345';
SET d1 = 1 + d2 * d3*100/10;
SET d2 = 6;
SET c2 = c1;
SET d3 = d1+d2;
SET rc1 = d1;
SET rc2 = d2-3;
SET rc3 = c2;
END;
Example 2:
CREATE PROCEDURE OUTPUTS(OUTPUT V1 INT,OUTPUT V2 BIGINT,
OUTPUT V3 FLOAT,OUTPUT V4 DOUBLE,
OUTPUT V5 DECIMAL(8,4),
OUTPUT V6 BINARY(20),OUTPUT V7 CHAR(20),
OUTPUT V8 VARCHAR(20),OUTPUT V9 NCHAR(40),
OUTPUT V10 NVARCHAR(40),OUTPUT V11 DATE,
OUTPUT V12 TIME,OUTPUT V13 TIMESTAMP)
LANGUAGE SQL
BEGIN
SET V1 = 1;
SET V2 = 7396;
SET V3 = 2.2;
SET V4 = 3.3;
SET V5 = 4.4;
SET V6 = 'ASSIGNMENT';
SET V7 = 'CHAR';
SET V8 = 'VARCHAR';
SET V9 = 'NCHAR';
SET V10 = 'NVARCHAR';
SET V11 = '2008-08-08';
SET V12 = '11:11:11';
SET V13 = '2008-08-08 11:11:11';
END;
Complex expression
A complex expression not only includes the assignment value in simple expression, but
also includes SQL functions. such as build-in function and user defined function.
Build-in function can be used on columns in a result set or columns that restrict rows
in a result set. Please refer to the SQL Command and Function Reference chapter 4 for
more detail information about DBMaker build-in function, which listed the
arguments and returned values for each function.
SQL control statements provide support for variables and flow of control statements
that can be used to control the sequence of statement execution. Statements such as IF
and CASE are used to conditionally execute blocks of SQL control statements, while
other statements, such as WHILE and REPEAT, are typically used to execute a set of
statements repetitively until a task is complete.
Although there are many types of SQL control statements, there are a few categories
into which these can be sorted:
Conditional statements
Loop statements
Goto statements
Return statements
Variable related SQL statements are used to declare variables and to assign values to
variables. There are a few types of variable related statements:
DECLARE <variable> statement in SQL stored procedures
These statements provide the necessary support required to make use of the other
types of SQL control statements and SQL statements that will make use of variable
values.
Conditional statements
Conditional statements are used to define what logic is to be executed based on the
status of some condition being satisfied. There are two types of conditional statements
supported in SQL stored procedures:
CASE
IF
These statements are similar; however the CASE statements extends the IF statement.
Searched case statement: used to enter into some logic based on the value of an
expression
The WHEN clause of the CASE statement defines the value that when satisfied
determines the flow of control.
The CASE statement for stored routines implements a complex conditional construct.
If a search_condition evaluates to true, the corresponding SQL statement list is
executed. If no search condition matches, the statement list in the ELSE clause is
executed. Each statement_list consists of one or more statements.
BEGIN
DECLARE v_workdept CHAR(3);
SET v_workdept = p_workdept;
CASE v_workdept
WHEN 'A00' THEN
UPDATE department SET deptname = 'D1';
WHEN 'B01' THEN
UPDATE department SET deptname = 'D2';
ELSE
UPDATE department SET deptname = 'D3';
END CASE;
END;
The examples provided above are logically equivalent, however it is important to note
that CASE statements with a searched-case-statement-when-clause can be very
powerful. Any supported SQL expression can be used here. These expressions can
contain references to variables, parameters and more.
Looping statements
Looping statements provide support for repeatedly executing some logic until a
condition is met. The following looping statements are supported in SQL control
statements:
FOR
LOOP
WHILE
REPEAT
The FOR statement is distinct from the others, because it is used to iterate over rows
of a defined result set, whereas the others are using for iterating over a series of SQL
statements until for each a condition is satisfied.
The FOR statement simplifies the implementation of a cursor and makes it easy to
retrieve a set of column values for a set of rows upon which logical operations can be
performed.
The statement list within a FOR statement is repeated as long as the CURSUR which
it fetch is not nil. statement_list consists of one or more statements. A FOR statement
can be labeled. end_label cannot be given unless begin_label also is present. If both are
present, they must be the same.
Example 1:Calculate the sum of all the values in table t1, then insert them into
table t2 in which c1 is the column name of table t1, so you can use both c1 and x.c1
forms to express c1 in the FOR syntax.
CREATE TABLE t1 (c1 INT);
CREATE TABLE t2 (c1 INT);
Example 2:In this example, x is a loop variable name, used to reference variable old;
cur is a cursor name, used in statements concerning cursors, for example, the update
statement and so on.
CREATE TABLE t1 (c1 INT);
Example 3:In this example, there is no loop variable name, so users only can use
variable old directly; cur is a cursor name, used in statements concerning cursors, for
example, the update statement and so on.
CREATE TABLE t1 (c1 INT);
Example 4:The function is same as above example, but the FOR statement does not
use cursor or loop variable name, so x.c1 cannot be used to express.
CREATE TABLE t1 (c1 INT);
CREATE TABLE t2 (c1 INT);
If the LOOP statement is used alone without a transfer of control statement, the series
of statements included in the loop will be executed indefinitely or until a database
condition occurs that raises a condition handler that forces a change in the control
flow or a condition occurs that is not handled that forces the return of the SQL stored
procedure.
LOOP implements a simple loop construct, enabling repeated execution of the
statement list, which consists of one or more statements. The statements within the
loop are repeated until the loop is exited; usually this is accomplished with a LEAVE
statement. A LOOP statement can be labeled. end_label cannot be given unless
begin_label also is present. If both are present, they must be the same.
BREAK;
END IF;
END LOOP;
CLOSE CUR;
SET sum = p_sum;
END;
With a WHILE statement, the loop is not entered if the while-loop-condition is false
at 1st pass. The REPEAT statement is useful alternative; however it is noteworthy that
while-loop logic can be rewritten as a REPEAT statement.
The REPEAT and UNTIL statements can be used to create a loop that continues
until some logical condition is met.
The REPEAT loop is somewhat easier to maintain because it is more obvious which
conditions will cause the loop to terminate. The LEAVE statement in a simple loop
could be anywhere, while the UNTIL statement is always associated with the END
REPEAT clause at the very end of the loop. Furthermore, we don't need to specify a
label for the REPEAT loop since the UNTIL condition is always specific to the
current loop. However, we still recommend using labels with REPEAT loops to
improve readability, especially if the loops are nested.
A REPEAT loop is always guaranteed to run at least once that is, the UNTIL
condition is first evaluated after the first execution of the loop. For loops that should
not run even once unless some condition is satisfied.
Goto statements
Goto statements are used to skip some statements and jump to any suitable statement.
However please use it gingerly. If the goto statement isn't used appropriately, the
executing flow will be disordered. When the usage of goto statements is incorrect, the
correlative error messages will be put into SQL stored procedure error message files
(sp_name.msg).
Label names can be same with input/output variable names, declared variable names
including common declare variables, cursor variables and condition variables.
Example2: The label name is same with common declared variable names
create procedure gsp1(in p1 int, out p2 char(30))
language sql
begin
set p2='more than or equal 10';
Users can define labels with the same name in different scopes. For labels, the
begin/end block and loops that SQLSP supports will define a new scope.
Example1: Define label variables in different begin/end blocks with the same name.
create procedure gsp5(out p1 int)
language sql
begin
lab: set p1=1;
begin
lab: set p1=2;
end;
end;
Example2: Define label variables in different loops with the same name.
create procedure gsp6(in p1 int)
language sql
begin
while p1<5 do
lab: set p1=p1+1;
end while;
while p1<15 do
lab: set p1=p1+1;
end while;
end;
The label can be defined in front of goto statements or in back of goto statements.
The goto statement can be used in if statements, loop statements and handler actions
of condition handlers.
When you use the goto statement, please note the following error cases:
Example1:
The label used in the goto statement must be already defined. In the following
example, the label used in the goto statement is not defined.
create procedure gsp12(in p1 int, out p2 int)
language sql
begin
if p1>10 then goto lab;
end if;
set p1= p1+1;
set p2=p1;
end;
Example2:
The label name cannot be repeated in the same scope. In the following example, the
label name is repeated in the same scope.
create procedure gsp13(in p1 int, out p2 int)
language sql
begin
if p1>10 then goto lab;
Using goto statements in handle actions of condition handlers, users must put the
handler action statement in a new begin/end block. At the same time, both the
goto statement and label should be in the new block.
Goto statements can't jump between begin blocks and end blocks.
Goto statements can't jump among loops that SQL stored procedure supports.
However in nested loops, goto statements can jump from the inner loop to the
outer loop.
In a loop, goto statements can't jump from the outside to the inside. This syntax
is supported in DB2, but DBMaker does not support it.
For begin/end blocks, goto statements can't jump from the outside to the inside
in the block.
Return statements
With the return statement, SQL stored procedures can exit the procedure executing
anywhere, and then an error message with user defined codes and message in dmSQL
will be printed.
Example2: The following example shows a return statement with goto statements.
dmSQL> @@create procedure ret_sp2(c1 int, out c2 int)
2> language sql
3> begin
4> declare v1 int default 0 ;
5> if c1 < 0 then
6> set v1 = -1;
7> goto LEXIT;
8> elseif c1 > 0 then
9> set v1 = 0;
10> goto LEXIT;
11> end if;
12> set c2 = c1;
13> LEXIT :
14> if v1 != 0 then
Return statements must be the follow format: return error_code, err_message, and
they can be anywhere in SQL stored procedure.
Users can define error codes by any integer constant and error message by any string
with single quotes . The error cods and error message are printed with user defined
error code and message.
Transfer of control statements are used to redirect the flow of control within a SQL
stored procedure. This unconditional branching can be used to cause the flow of
control to jump from one point to another point, which can either precede or follow
the transfer of control statement. The supported transfer of control statements in SQL
stored procedures are:
ITERATE
LEAVE
Transfer of control statements can be used anywhere within a SQL stored procedure,
however ITERATE and LEAVE are generally used in conjunction with a LOOP
statement or other looping statements.
LANGUAGE SQL
BEGIN
DECLARE v_deptno CHAR(3);
DECLARE v_deptname VARCHAR(29);
DECLARE c1 CURSOR FOR SELECT deptno, deptname FROM department
ORDER BY deptno;
OPEN c1;
LOOP
FETCH c1 INTO v_deptno, v_deptname;
IF v_deptno = NULL THEN LEAVE;
ELSEIF v_deptno = 'D11' THEN INSERT INTO department
(deptno, deptname) VALUES ('NEW', v_deptname);
ITERATE;
ELSE
ITERATE;
END IF;
END LOOP;
CLOSE c1;
END;
In the example, the ITERATE statement is used to return the flow of control to the
LOOP statement defined with loop when a column value in a fetched row matches a
certain value. The position of the ITERATE statement ensures that no values are
inserted into the department table.
Labels can optionally be used to name any control statement in a SQL stored
procedure, including compound statements and loops. By referencing labels in other
statements you can force the flow of execution to jump out of a compound statement
or loop or additionally to jump to the beginning of a compound statement or loop.
Labels can be referenced by the ITERATE, and LEAVE statements.
Optionally you can supply a corresponding label for the END of a compound
statement. If an ending label is supplied, it must be same as the label used at its
beginning.
Each label must be unique within the body of a SQL stored procedure.
Labels can also be used to avoid ambiguity if a variable with the same name has been
declared in more than one compound statement in the stored procedure. A label can
be used to qualify the name of a SQL variable.
Example 1:
CREATE PROCEDURE test3
LANGUAGE SQL
L1: BEGIN
...
L2: BEGIN
...
END L2;
END L1;
lable2: BEGIN
IF V1 > 100 THEN
SET V2 = -2;
LEAVE lable1;
END IF;
lable3: BEGIN
IF V1 > 50 THEN
SET V2 = -3;
LEAVE lable1;
END IF;
SET V1 = V1+1;
END lable3;
END lable2;
The common variable is defined by base data type, such as INT, CHAR, FLOAT and
so on, which are supported by SQL stored procedures. Every variable has its available
scope. The variable defined in the previous level can be used in the next level, but the
variable defined in the next level cannot be used in the previous level.
In SQL stored procedures, to indicate a new level, you can enclose compound
statements by using the BEGIN…END statement.
Example 1:
CREATE PROCEDURE test41(OUT res1 INT, OUT res2 INT, OUT res3 INT)
LANGUAGE SQL
L1: BEGIN
DECLARE c1, c2 INT;
SET c1 = 1; #set a value in level L1
L2: BEGIN
DECLARE c1 INT;
SET c1 = 2;
SET c2 = 3;
SET res3 = c1; #C1 is redefined in level L2, so the value in
level L1 is shielded, res3 = 2.
END L2;
SET res1 = c1; #When the assignment statements in level L2 are end
c1 will regains the value in level L1, so res1 = 1.
SET res2 = c2; #C2 is only defined in L1, and the changes in level
L2 also will affect the level L1, so res2 = 3.
END L1;
#As the influence scope is limited in the FOR statement, so the value
of c1 still is 10 when the FOR statement is end.
END;
To perform error handling or to help you debug your SQL stored procedures, you
might find it useful to test the value of the SQLCODE or SQLSTATE values, return
these values as output parameters or insert these values into a table to provide basic
tracing support.
When you need to check result run the statement, please use the SQLCODE variable
firstly, Then you can use SQLSTATE variable to check detailed error message, So you
can understand the execution states of the statement accurately.
BEGIN
DECLARE retcode INTEGER DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION, SQLWARNING, NOT FOUND SET
retcode = SQLCODE;
END;
3. Keep the cursor open for the client application - do not close it
OPEN cur;
END;
Example 2:
########################################################################
# Module Name = RETU.SP
# Purpose = Store Procedure testing program
# 1. Test keyword "RETURN" in Store Procedure
# Function = 1. declare r1~r14 for pass parameter
# 2. create table tb_1 and insert data into tb_1
# 3. use cursor get data from tb_1
# Use Database : DBNAME
# table : TB_1(V1 int,V2 smallint,V3 INT,V4 FLOAT,V5 DOUBLE,
# V6 DECIMAL(20,4),V7 BINARY(10),V8 CHAR(20),
# V9 VARCHAR(20),V10 NCHAR(40),
# V11 NVARCHAR(40),V12 DATE,V13 TIME,V14 TIMESTAMP)
########################################################################
CREATE PROCEDURE RETU
LANGUAGE SQL
BEGIN
DECLARE cur CURSOR WITH RETURN FOR select * from tb_1;
OPEN CUR ;
END;
The following is the result of call RETU:
dmSQL> call retu;
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14
=== === === === === ==== ==== === === ========= ======= === === ===
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* 汉* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* 汉* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* 汉* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* 汉* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* ba00ba00d* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* ba00ba00d* 6e0076006* 20* 11* 200*
1 2 3 *00 *00 2.33 626* ch* va* 6e0063006* 6e0076006* 20* 11* 200*
11 rows selected
If you want to return status of stored procedure, you should need add 'RETURN
STATUS' before LANGUAGE SQL.
Example: The following is an example of a SQL stored procedure with return status.
CREATE PROCEDURE ret_status RETURN STATUS
LANGUAGE SQL
BEGIN
END;
Anonymous stored procedure is a special kind of SQL stored procedure similar to the
Anonymous SQL Block. It can let user execute more than one SQL statement (batch
of SQL) once in the client side, and supports all SQL syntax blocks including
variables, grammar logic and cursors etc,.The anonymous stored procedure cannot
using the stored procedure parameters and specific commands belong to dmSQL
command line tool (such as: set etc.). Users must set block delimiter before writing the
anonymous SQL block in dmSQL, otherwise, it will return error. For more
information on anonymous stored procedure's variables and syntax logic, please refer
to the information in Database Administrator's Guide Chapter 12, Stored Procedures.
NOTE Anonymous stored procedures’ compound statements are bounded by the keywords
"BEGIN " and "END".
Compared with the SQL stored procedure, there is no name in the anonymous stored
procedure, and cannot be referenced by other database objects. That is to say, the
execution of an anonymous stored procedure is instant. When an anonymous stored
procedure has completed its creation successfully, it enters into the execution state.
Once it's executed successfully, DBMaker will delete them immediately. The
information of anonymous stored procedure will not be saved to the system table
SYSPROCINFO, also cannot be permanently stored in DBMaker for reuse.
Anonymous stored procedure reduces the time interval between the code updates and
program execution, thus improves the efficiency of problem diagnosis, prototyping
and testing code execution, provides the convenient for the multiple tasks updates and
execution.
Example
Example:
CREATE PROCEDURE dym_test1
LANGUAGE SQL
BEGIN
DECLARE str char(128);
SET str= 'insert into t1 values(5)';
EXECUTE IMMEDIATE str;
END;
PREPARE statement
Example:
CREATE PROCEDURE dym_test2
LANGUAGE SQL
BEGIN
DECLARE str char(128);
SET str= 'insert into t1 values(5)';
EXECUTE statement
Associate input SQL parameters and output targets with a prepared statement and
execute the statement.
Example 1:
CREATE PROCEDURE dym_test3(IN val INT)
LANGUAGE SQL
BEGIN
DECLARE str char(128);
SET str= 'insert into t1 values(?)';
Example 2:
CREATE PROCEDURE dym_test4(IN val INT, OUT co INT)
LANGUAGE SQL
BEGIN
DECLARE str char(128);
SET str= 'select COUNT(*) from t1 where c1=?';
Example :
CREATE PROCEDURE dym_test2
LANGUAGE SQL
BEGIN
DECLARE str char(128);
SET str= 'insert into t1 values(5)';
Associate input dynamic parameters with a cursor and open the cursor.
OPEN cur;
WHILE SQLCODE = 0 DO
SET sum = sum + val;
FETCH cur INTO val;
END WHILE;
CLOSE cur;
If you create a temp stored procedure in multi-user mode , the temp stored procedure
will be dropped when the connection is disconnected; if you create temp procedure in
signal user mode, it can be dropped when database is started. When you disconnect
the connection which create some temp stored procedures, the temp stored procedure
will not be dropped immediately, and it will be dropped in ten minutes. User can
replace temp sp created by him, When database shutdown or database crash, clear all
temp sp when database restart.
Different connections can create local temp procedures with the same name.
Temp sp can be replaced by permanent sp with the same name. But permanent
sp can't be replaced by temp sp.
If SYSADM create a permanent sp named XX, other user also can create any type
sp named XX.
Syntax:
CREATE [OR REPLACE] [GLOBAL\LOCAL] TEMP PROCEDURE <sp_name>
[RETURNS STATUS]
LANGUAGE SQL
BEGIN
<sp_body>
END;
Example3: create a local temp stored procedure with the same name tsp2,and call it
dmSQL> use 2;
dmSQL> connect to test sysadm;
dmSQL> @@
2> /* create local temp sp with the same name */
3> create local temp procedure tsp2(out c1 int)
4> language sql
5> begin
6> set c1 = 2;
7> end;
8> @@
dmSQL> call tsp2(?);
5> begin
6> end;
7> @@
Example5: Other user create a global temp stored procedure with the same name tsp3
dmSQL> use 3;
dmSQL> connect to test xu;
dmSQL> @@
2> /* create global temp sp with the same name by sysadm */
3> create global temp procedure tsp3
4> language sql
5> begin
6> end;
7> @@
INSERT statement
The following example shows using the insert statement in SQL stored procedure.
Example: creating a SQL stored procedure, complete the table insert data manipulate
########################################################################
# Module Name = INPUTS.SP
# Purpose = Store Procedure testing program
# 1. Test INPUT parameter store procedure
Select statement
The following example shows using the select statement in a SQL stored procedure.
Example:
########################################################################
# Module Name = OUTPUTS.SP
# Purpose = Store Procedure testing program
# 1. Test OUTPUT parameter store procedure
# 2. Test all type which can use in Store Procedure
# Function = 1. create table OUTPUTS and insert data into OUTPUTS
# 2. use cursor get data from OUTPUTS and pass data to
OUTPUT parameter
# Use Database : DBNAME
# table : OUTPUTS(V1 int, V2 BIGINT, V3 smallint,V4 INT,
# V5 double, V6 DOUBLE, V7 DECIMAL(20,4),
Create statement
The following example demonstrates how to use the create statement in SQL stored
procedure.
Drop statement
The following example demonstrates how to use the drop statement in SQL stored
procedure.
END IF;
END;
Trace functionality to help users trace the execution of SQL stored procedures for
debugging. Turn on and use the TRACE function to place variables for tracing and
print messages. After the SQL stored procedure executes, all trace information will be
written to a file named _sptrace.log in the DBMaker bin directory .
Expression must use single quotes " ' " and support all data types, but the BINARY,
NCHAR, NVARCHAR data types are shown in hexadecimal format.
Example:
CREATE PROCEDURE INPUTS(INPUT V1 int, INPUT V2 BIGINT,
INPUT V3 smallint, INPUT V4 INT,
INPUT V5 FLOAT, INPUT V6 DOUBLE,
INPUT V7 DECIMAL(20,4),
INPUT V8 BINARY(20), INPUT V9 CHAR(20),
INPUT V10 VARCHAR(20), INPUT V11 NCHAR(40),
INPUT V12 NVARCHAR(40), INPUT V13 DATE,
INPUT V14 TIME, INPUT V15 TIMESTAMP,
INPUT V16 REAL)
LANGUAGE SQL
BEGIN
TRACE ON;
TRACE('V1=', V1);
TRACE('V2=', V2);
TRACE('V3=', V3);
TRACE('V4=', V4);
TRACE('V5=', V5);
TRACE('V8=', V8);
TRACE('V9=', V9);
TRACE('V12=', V12);
TRACE('V13=', V13);
TRACE('V14=', V14);
TRACE('V15=', V15);
TRACE('V16=', V16);
TRACE OFF;
INSERT INTO INPUTS VALUES(V1,V2,V3,V4,V5,V6,V7,V8,V9,
V10,V11,V12,V13,V14,V15,V16);
END;
After call
input(1,7396,2,3,4,5,6,'binary','char','varchar','NCHAR','NVARCHAR','2008-01-
01','11:11:11','2008-01-01 11:11:11',' 123.456') _sptrace.log adds log as follows
INPUTS 47: Begin trace ====>
INPUTS 48: V1=1
INPUTS 49: V2=7396
INPUTS 50: V3=2
INPUTS 51: V4=3
INPUTS 52: V5=4
INPUTS 53: V8=62696e617279
INPUTS 54: V9=char
INPUTS 55: V12=4e005600410052004300480041005200
INPUTS 56: V13=2008-01-01
INPUTS 57: V14=11:11:11
INPUTS 58: V15=2008-01-01 11:11:11.000
INPUTS 59: V16=123.4560012817383
To assist you in developing SQL stored procedures, several examples of SQL stored
procedures are available for reference.
Creating SQL stored procedures is similar to creating any database object in that it
consists of executing a SQL statement. SQL stored procedures are created by
First, write the SQL stored procedure and save it to a file, then use DBMaker tools
like dmSQL to store this SQL stored procedure in the database.
NOTE DBMaker SQL stored procedure can only by call an external file (*.sp ) to
create, cannot directly write it in the dmSQL command line tool.
The above examples show how to create SQL stored procedure from file using
dmSQL tool.
In DBMaker, users can create SQLSP not only from files, but also in dmSQL directly
Users can call and drop the SQLSP which owned to himself, and execute SQLSP
which granted privilege.
SQLSP contains more than one SQL statements, and each statement is end of '; '. So
dmSQL must support block delimiter. Block delimiter can be a combination of a-z, A-
Z, @, %, ^, and contains two characters at least and seven characters at most, but can’t
be set/block/delimiter. We don't forbid user to set block delimiter as other keywords
in SQL statement (create, table…), but we suggest user use non-alphanumeric sign
like @, % and ^. In block delimiter, '; ' doesn't denote end of the input. In addition,
users must set block delimiter before writing SQLSP in dmSQL, otherwise, it will
return error.
NOTE # is not comment character in dmSQL, because table name maybe contains '#',
we support --, // for line comment and /**/ for block comment. We also advise
users not to use '#'for comment character in SQLSP file, though '#' is comment
when users create SQLSP from files.
NOTE If the command of creating procedure is more than 4K, dmSQL don't save it as
history command, so user can't use history command.
ODBC API supports creating permanent and temp sp, users can write AP with
ODBC to support creating any type of the SQL Procedure. For example,
int main()
{
…
SQLExecDriect(hstmt, CRELTSP, SQL_NTS);
DBMaker provides three languages for creating stored procedures: SQL, ESQL/C and
Java. The following is an illustrator for creating a stored procedure using SQL
language.
2. Click the Create button. The Introduction window of the Create Stored
Procedure wizard appears.
4. Select SQL language to use for writing the stored procedure by clicking the
SQL radio button.
5. Click the Next button. The Final Review window appears. Input the SQL
statement or click the Import button to import a SQL statement from a file.
6. Click the Import button. The Open window appears. Import files from any
source, including the SPDIR directory of other databases on the server or
network drives. Enter the path in the File name field, or browse the directory
tree until the desired path is found.
9. If the SQL stored procedure compiles correctly, the following message appears.
You can invoke a stored procedure in dmSQL tool, or using a trigger action. The user
must have the privileges required to execute the Call PROCEDURE statement for a
SQL stored procedure.
CREATE PROCEDURE call1(IN inval INT, OUT outval1 INT, OUT outval2 INT)
LANGUAGE SQL
BEGIN
CALL CASE_TEST_1(inval, outval1, outval2);
END;
0 rows selected
dmSQL> CREATE PROCEDURE FROM 'D:\SPDIR\INSERT_1.SP';
dmSQL> CALL INSERT_1;
dmSQL> SELECT * FROM TB_1;
NAME PHONE
==================== ====================
JONTH 1234567
1 rows selected
Users can call a SQL stored procedure by trigger action: first you need create a table
for example tb_2(name char(20),phone char(20)), then create a trigger for tb_2 as:
CREATE TRIGGER TRG_1 AFTER INSERT ON TB_2 FOR EACH ROW (CALL INSERT_1);
NOTE Double-clicking a SQL stored procedure in the right panel displays the
same window.
2. Click the Execute button. The result of the executed SQL stored procedure
appears.
3. Click the OK button.
Example: Dropping SQL stored procedure in the dmSQL command line tool:
dmSQL> DROP PROCEDURE PROC1;
dmSQL> DROP PROCEDURE USER1.PROC1;
The first statement drops the stored procedure proc1,and the second statement drops
the stored procedure user1.proc1.
4. Click the Yes button to drop the stored procedure or click the Cancel button
to terminate the dropping process.
Example :
dmSQL> select * from sysprocinfo;
dmSQL> select * from SYSPROCPARAM;
The owner or a user with DBA or higher authority can also revoke execute privilege
on a stored procedure for other users.
Example 1:
user1 creates a stored procedure called proc1 and grants the execute privilege to user2
using dmSQL:
dmSQL> GRANT EXECUTE ON PROCEDURE proc1 TO user2;
Example 2:
user1 creates a stored procedure called proc1 and grants the execute privilege to
PUBLIC using dmSQL:
Example 3:
user1 revokes the execute privilege from user2 using dmSQL:
dmSQL> REVOKE EXECUTE ON PROCEDURE proc1 FROM user2;
Example 4:
user1 revokes the execute privilege from PUBLIC using dmSQL:
dmSQL> REVOKE EXECUTE ON PROCEDURE proc1 FROM PUBLIC;
The keyword DB_SPLog is used by client users to set the directory they prefer to
receive error message files and trace log files, transmitted from the database server
while creating or executing stored procedures.
Example 1:
To set the default path of dynamic link library files for stored procedures to
/usr1/dbmaker/data/SP add the following line in the dmconfig.ini file:
DB_SPDIR=/usr1/DBMaker/data/SP
Example 2:
To set the stored procedure log file directory to c:\usr\jerry\data\SP add the following
line in the dmconfig.ini file:
DB_SPLOG=c:\usr\jerry\data\SP
7 SQL Stored
Procedures Migration
Stored procedures are easily migrated to other databases using the unload and load
commands.
After executing this command, the system generates two files named call.b0 and call.so
in the d:\spdir\... directory. The call.b0 file stores BLOB data. The call.s0 file stores
the script.
8 Restriction on SQL
Stored Procedures
SET d2 = 0x124C;
SET d2 = 1.2345E2;
SET c1 = '1234';
5. Using SET statement to assign variable will check the type of variables,
different attribute types cannot be assigned each other, that means users cannot
assign a character data to a numerical variable, and vice versa. For the
assignment between the numerical variables, if necessary assign a decimal to a
integer value, it will automatically rounding decimal part.
6. String can only enclosed with two single quotation marks (" ' "), and with the
following conditions:
If a string have two consecutive "'" , it means that one of the "'" is
string content,
Example
SET c1 = '12345''6789'; -- c1 = 12345'6789
String can have any double quotation marks "" ", it's just a part of the
string and will not be interpreted as a string delimiter.
Example:
SET c1 = '12"34"56"78"9'; -- c1 = 12"34"56"78"9
Example:
SET c1 = '12345\6789'; -- c1 = 12345\6789
However, if the character is the comment symbol "#" after the backslash, it would
be escape as an ordinary character "#".
Example:
SET c1 = '12345\#6789'; -- c1 = 12345#6789
Example:
SET c1 = '12345
6789';
then
c1 = 12345
6789
If the character is the backslash "\" before the carriage return line feed
symbol, it denotes the carriage return line feed will be removed, and
connect the upper and lower two lines at the same time.
Example:
SET c1 = '12345\
6789';
then
c1 = 123456789
7. Support SET n1, n2, …. = select c1, c2, … from t1 syntax, and only get the
first record of select statement when performing. If the assigned variable number
is not equal with the field number in the result set, it will accordance with the
following rules:
There are n-variable numbers , m- result set field numbers , if n<=m, then it will
get the result set from 1 to n, otherwise it will get all result set, and assign
NULL to the extra variables. It needs to check the result set field type whether
match the type of corresponding variable, if not match, it will occur error massage.
Example:
SET sum = select count(*) from t1;
9. The DB_SPLog keyword in the dmconfig.ini file can only be used on the
client side, but useless for the TRACE information of SQL Stored Procedure,
TRACE function only accept the default path which is DBMaker
implementation directory on the server side, and information will be written
into the _sptrace.log file of this directory by default.
10. SQL stored procedure script can use any extension names, even without any
extension names.
11. When table name or field name is the same as variable name which in SQL
Stored Procedure statement, it needs to bracket the table name or field name
with double quotation marks " " " to distinguish the variable name.
Example:
DECLARE c1 INT;
ABORT BACKUP
BEGIN BACKUP
BEGIN WORK
END BACKUP
13. If WARNING or ERROR messages are generated when user perform SQL
Stored Procedure. By default, WARNING message will be ignored and continue
to perform, but the final WARNING message will return to the user The ERROR
message will be discontinued and return to the user. If a WARNING and ERROR
messages simultaneous occur, it will only return ERROR message.
CASE
ELSE charc3
END);
15. Not support the client syntax for example: set client_char_set 'big5', user can
use dynamic SQL to achieve the same syntax
16. The following is SQL Stored Procedure reserved keywords, the variable names
cannot be set to the following keywordsor the reserved keywords in the SQL
Command and Function Reference. (may have intersection).
19. Not support the length more than 10,240 bytes static SQL statement within a stored
procedure.