Interbase 6 - Embedded SQL Guide
Interbase 6 - Embedded SQL Guide
Embedded
SQL Guide
Borland/INPRISE
100 Enterprise Way, Scotts Valley, CA 95066 http://www.interbase.com
November 12, 1999 (C:\TechPubs60\60DocSet\Doc\EmbedSQL\EmbedSQLTitle.fm5)
Inprise/Borland may have patents and/or pending patent applications covering subject matter in this
document. The furnishing of this document does not convey any license to these patents.
Copyright 1999 Inprise/Borland. All rights reserved. All InterBase products are trademarks or registered
trademarks of Inprise/Borland. All Borland products are trademarks or registered trademarks of
Inprise/Borland. Other brand and product names are trademarks or registered trademarks of their
respective holders.
1INT0055WW21000 6E1R0699
Table of Contents
List of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
List of Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
iv INTERBASE 6
TABLE OF CONTENTS
vi INTERBASE 6
TABLE OF CONTENTS
viii INTERBASE 6
TABLE OF CONTENTS
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
x INTERBASE 6
List of Tables
xii INTERBASE 6
List of Figures
Example 2.1 Using host-language data structures to reference table columns . . .25
Example 2.2 Using SQL to read table data into a C struct . . . . . . . . . . . . . .25
Note The Embedded SQL Guide focuses on embedded SQL and DSQL programming in
C or C++. It does not address Delphi-specific topics.
Chapter Description
Chapter 1, “Using the Embedded SQL Guide” Introduces the structure of the book and describes its
intended audience.
Chapter 2, “Application Requirements” Describes elements common to programming all SQL and
DSQL applications.
Chapter 3, “Working with Databases” Describes using SQL statements that deal with databases.
Chapter 4, “Working with Transactions” Explains how to use and control transactions with SQL
statements.
Chapter 5, “Working with Data Definition Describes how to embed SQL data definition statements in
Statements” applications.
Chapter 6, “Working with Data” Explains how to select, insert, update, and delete standard
SQL data in applications.
Chapter 7, “Working with Dates” Describes how to select, insert, update, and delete DATE, TIME,
and TIMESTAMP data in applications.
Chapter 8, “Working with Blob Data” Describes how to select, insert, update, and delete Blob data
in applications.
Chapter 9, “Using Arrays” Describes how to select, insert, update, and delete array data
in applications.
Chapter 10, “Working with Stored Procedures” Explains how to call stored procedures in applications.
Chapter 11, “Working with Events” Explains how triggers interact with applications. Describes
how to register interest in events, wait on them, and respond
to them in applications.
Chapter 12, “Error Handling and Recovery” Describes how to trap and handle SQL statement errors in
applications.
TABLE 1.1 Chapters in the InterBase 6 Embedded SQL Guide
18 INTERBASE 6
SAMPLE DATABASE AND APPLICATIONS
Chapter Description
Chapter 13, “Using Dynamic SQL” Describes how to write DSQL applications.
Chapter 14, “Preprocessing, Compiling, and Linking” Describes how to convert source code into an executable
application.
Appendix A, “InterBase Document Conventions” Lists typefaces and special characters used in this book to
describe syntax and identify object types.
TABLE 1.1 Chapters in the InterBase 6 Embedded SQL Guide
20 INTERBASE 6
CHAPTER
Application Requirements
Chapter2
2
This chapter describes programming requirements for InterBase SQL and dynamic SQL
(DSQL) applications. Many of these requirements may also affect developers moving
existing applications to InterBase.
Dynamic SQL applications, those applications that build SQL statements at run time, or
enable users to build them, have additional requirements. For more information about
DSQL requirements, see “DSQL requirements” on page 30.
For more information about using gpre, see Chapter 14, “Preprocessing, Compiling,
and Linking.”
22 INTERBASE 6
REQUIREMENTS FOR ALL APPLICATIONS
One host variable must be declared for every column of data accessed in a database. Host
variables may either be declared globally like any other standard host-language variable,
or may appear within an SQL section declaration with other global declarations. For more
information about reading from and writing to host variables in SQL programs, see
Chapter 6, “Working with Data.”
Host variables used in SQL programs are declared just like standard language variables.
They follow all standard host-language rules for declaration, initialization, and
manipulation. For example, in C, variables must be declared before they can be used as
host variables in SQL statements:
int empno; char fname[26], lname[26];
For compatibility with other SQL variants, host variables can also be declared between
BEGIN DECLARE SECTION and END DECLARE SECTION statements.
4 Section declarations
Many SQL implementations expect host variables to be declared between BEGIN DECLARE
SECTION and END DECLARE SECTION statements. For portability and compatibility,
InterBase supports section declarations using the following syntax:
EXEC SQL
BEGIN DECLARE SECTION;
<hostvar>;
. . .
EXEC SQL
END DECLARE SECTION;
For example, the following C code fragment declares three host variables, empno, fname,
and lname, within a section declaration:
EXEC SQL
BEGIN DECLARE SECTION;
int empno;
char fname[26];
char lname[26];
EXEC SQL
END DECLARE SECTION;
Additional host-language variables not used in SQL statements can be declared outside
DECLARE SECTION statements.
For example, the following statements declare two host variables, fname, and lname,
based on two column definitions, FIRSTNAME, and LASTNAME, in an employee database:
BASED ON EMP.FIRSTNAME fname;
BASED ON EMP.LASTNAME lname;
Embedded in a C or C++ program, these statements generate the following host- variable
declarations during preprocessing:
char fname[26];
char lname[26];
24 INTERBASE 6
DECLARING AND INITIALIZING DATABASES
struct
{
char fname[25];
char lname[25];
char street[30];
char city[20];
char state[3];
char zip[11];
} billing_address;
SQL recognizes data members in structures, but information read from or written to a
structure must be read from or written to individual data members in SQL statements. For
example, the following SQL statement reads data from a table into variables in the C
structure, BILLING_ADDRESS:
EXEC SQL
SELECT FNAME, LNAME, STREET, CITY, STATE, ZIP
INTO :billing_address.fname, :billing_address.lname,
:billing_address.street, :billing_address.city,
:billing_address.state, :billing_address.zip
FROM ADDRESSES WHERE CITY = ’Brighton’;
A separate statement should be used for each database. For example, the following
statements declare a handle, DB1, for the employee.gdb database, and another handle,
DB2, for employee2.gdb:
EXEC SQL
SET DATABASE DB1 = ’employee.gdb’;
EXEC SQL
SET DATABASE DB2 = ’employee2.gdb’;
Once a database handle is created and associated with a database, the handle can be used
in subsequent SQL database and transaction statements that require it, such as CONNECT.
Note SET DATABASE also supports user name and password options. For a complete
discussion of SET DATABASE options, see Chapter 3, “Working with Databases.”
26 INTERBASE 6
DECLARING AND INITIALIZING DATABASES
Using CONNECT
The CONNECT statement attaches to a database, opens the database, and allocates system
resources for it. A database must be opened before its tables can be used. To include
CONNECT in a program, use the following syntax:
EXEC SQL
CONNECT handle;
A separate statement can be used for each database, or a single statement can connect to
multiple databases. For example, the following statements connect to two databases:
EXEC SQL
CONNECT DB1;
EXEC SQL
CONNECT DB2;
Once a database is connected, its tables can be accessed in subsequent transactions. Its
handle can qualify table names in SQL applications, but not in DSQL applications. For a
complete discussion of CONNECT options and using database handles, see Chapter 3,
“Working with Databases.”
SQL statements
An SQL application consists of a program written in a host language, like C or C++, into
which SQL and dynamic SQL (DSQL) statements are embedded. Any SQL or DSQL
statement supported by InterBase can be embedded in a host language. Each SQL or
DSQL statement must be:
g Preceded by the keywords EXEC SQL.
g Ended with the statement terminator expected by the host language. For example, in C
and C++, the host terminator is the semicolon (;).
For a complete list of SQL and DSQL statements supported by InterBase, see the
Language Reference.
Closing transactions
Every transaction should be closed when it completes its tasks, or when an error occurs
that prevents it from completing its tasks. Failure to close a transaction before a program
ends can cause limbo transactions, where records are entered into the database, but are
neither committed or rolled back. Limbo transactions can be cleaned up using the
database administration tools provided with InterBase.
28 INTERBASE 6
CLOSING TRANSACTIONS
Accepting changes
The COMMIT statement ends a transaction, makes the transaction’s changes available to
other users, and closes cursors. A COMMIT is used to preserve changes when all of a
transaction’s operations are successful. To end a transaction with COMMIT, use the
following syntax:
EXEC SQL
COMMIT TRANSACTION name;
For a complete discussion of SQL transaction control, see Chapter 4, “Working with
Transactions.”
Undoing changes
The ROLLBACK statement undoes a transaction’s changes, ends the current transaction,
and closes open cursors. Use ROLLBACK when an error occurs that prevents all of a
transaction’s operations from being successful. To end a transaction with ROLLBACK, use
the following syntax:
EXEC SQL
ROLLBACK TRANSACTION name;
For example, the following statement rolls back a transaction named MYTRANS:
EXEC SQL
ROLLBACK TRANSACTION MYTRANS;
To roll back an unnamed transaction (i.e., the default transaction), use the following
statement:
EXEC SQL
ROLLBACK;
For a complete discussion of SQL transaction control, see Chapter 4, “Working with
Transactions.”
Closing databases
Once a database is no longer needed, close it before the program ends, or subsequent
attempts to use the database may fail or result in database corruption. There are two ways
to close a database:
g Use the DISCONNECT statement to detach a database and close files.
g Use the RELEASE option with COMMIT or ROLLBACK in a program.
DISCONNECT, COMMIT RELEASE, and ROLLBACK RELEASE perform the following tasks:
g Close open database files.
g Close remote database connections.
g Release the memory that holds database descriptions and InterBase engine-compiled
requests.
Note Closing databases with DISCONNECT is preferred for compatibility with the SQL-92
standard.
For a complete discussion of closing databases, see Chapter 3, “Working with
Databases.”
DSQL requirements
DSQL applications must adhere to all the requirements for all SQL applications and meet
additional requirements as well. DSQL applications enable users to enter ad hoc SQL
statements for processing at run time. To handle the wide variety of statements a user
might enter, DSQL applications require the following additional programming steps:
g Declare as many extended SQL descriptor areas (XSQLDAs) as are needed in the
application; typically a program must use one or two of these structures. Complex
applications may require more.
g Declare all transaction names and database handles used in the program at compile time;
names and handles are not dynamic, so enough must be declared to accommodate the
anticipated needs of users at run time.
g Provide a mechanism to get SQL statements from a user.
g Prepare each SQL statement received from a user for processing.
PREPARE loads statement information into the XSQLDA.
g EXECUTE each prepared statement.
30 INTERBASE 6
DSQL REQUIREMENTS
EXECUTE IMMEDIATE combines PREPARE and EXECUTE in a single statement. For more
information, see the Language Reference.
In addition, the syntax for cursors involving Blob data differs from that of cursors for
other datatypes. For more information about Blob cursor statements, see the Language
Reference.
Declaring an XSQLDA
The extended SQL descriptor area (XSQLDA) is used as an intermediate staging area for
information passed between an application and the InterBase engine. The XSQLDA is used
for either of the following tasks:
g Pass input parameters from a host-language program to SQL.
g Pass output, from a SELECT statement or stored procedure, from SQL to the host-language
program.
A single XSQLDA can be used for only one of these tasks at a time. Many applications
declare two XSQLDAs, one for input, and another for output.
The XSQLDA structure is defined in the InterBase header file, ibase.h, that is automatically
included in programs when they are preprocessed with gpre.
IMPORTANT DSQL applications written using versions of InterBase prior to 3.3 use an older SQL
descriptor area, the SQLDA. The SQLDA and the gpre -sqlda switch are no longer supported.
Older applications should be modified to use the XSQLDA.
To create an XSQLDA for a program, a host-language datatype of the appropriate type must
be set up in a section declaration. For example, the following statement creates two
XSQLDA structures, inxsqlda, and outxsqlda:
. . .
EXEC SQL
BEGIN DECLARE SECTION;
XSQLDA inxsqlda;
XSQLDA outxsqlda;
. . .
EXEC SQL
END DECLARE SECTION;
. . .
DSQL limitations
DSQL enables programmers to create flexible applications that are capable of handling a
wide variety of user requests. Even so, not every SQL statement can be handled in a
completely dynamic fashion. For example, database handles and transaction names must
be specified when an application is written, and cannot be changed or specified by users
at run time. Similarly, while InterBase supports multiple databases and multiple
simultaneous transactions in an application, the following limitations apply:
g Only a single database can be accessed at a time.
g Transactions can only operate on the currently active database.
g Users cannot specify transaction names in DSQL statements; instead, transaction names
must be supplied and manipulated when an application is coded.
EXEC SQL
SET DATABASE DB1 = :fname1;
EXEC SQL
32 INTERBASE 6
DSQL LIMITATIONS
For a complete discussion of SET DATABASE, see Chapter 3, “Working with Databases.”
printf("\nSQL> ");
gets(userstatement);
EXEC SQL
EXECUTE IMMEDIATE TRANSACTION first userstatement;
. . .
For complete information about named transactions, see Chapter 4, “Working with
Transactions.”
Preprocessing programs
After an SQL or DSQL program is written, and before it is compiled and linked, it must
be preprocessed with gpre, the InterBase preprocessor. gpre translates SQL statements and
variables into statements and variables that the host-language compiler accepts. For
complete information about preprocessing with gpre, see Chapter 14, “Preprocessing,
Compiling, and Linking.”
34 INTERBASE 6
CHAPTER
Declaring a database
Before a database can be opened and used in a program, it must first be declared with
SET DATABASE to:
This database declaration identifies the database file, employee.gdb, as a database the
program uses, and assigns the database a handle, or alias, DB1.
If a program runs in a directory different from the directory that contains the database
file, then the file name specification in SET DATABASE must include a full path name, too.
For example, the following SET DATABASE declaration specifies the full path to
employee.gdb:
EXEC SQL
SET DATABASE DB1 = ’/interbase/examples/employee.gdb’;
If a program and a database file it uses reside on different hosts, then the file name
specification must also include a host name. The following declaration illustrates how a
Unix host name is included as part of the database file specification on a TCP/IP network:
EXEC SQL
SET DATABASE DB1 = ’jupiter:/usr/interbase/examples/employee.gdb’;
On a Windows network that uses the Netbeui protocol, specify the path as follows:
EXEC SQL
SET DATABASE DB1 = ’//venus/C:/Interbase/examples/employee.gdb’;
36 INTERBASE 6
DECLARING A DATABASE
IMPORTANT This use of database handles applies only to embedded SQL applications. DSQL
applications cannot access multiple databases simultaneously.
IMPORTANT The file specification that follows the COMPILETIME keyword must always be a
hard-coded, quoted string.
38 INTERBASE 6
DECLARING A DATABASE
When SET DATABASE uses the COMPILETIME clause, but no RUNTIME clause, and does not
specify a different database file specification in a subsequent CONNECT statement, the
same database file is used both for preprocessing and run time. To specify different
preprocessing and runtime databases with SET DATABASE, use both the COMPILETIME and
RUNTIME clauses.
The file specification that follows the RUNTIME keyword can be either a hard-coded,
quoted string, or a host-language variable. For example, the following C code fragment
prompts the user for a database name, and stores the name in a variable that is used later
in SET DATABASE:
. . .
char db_name[125];
. . .
printf("Enter the desired database name, including node
and path):\n");
gets(db_name);
EXEC SQL
SET DATABASE EMP = COMPILETIME ’employee.gdb’ RUNTIME :db_name;
. . .
The EXTERN keyword is used in a multi-module program to signal that SET DATABASE in
one module is not an actual declaration, but refers to a declaration made in a different
module. gpre uses this information during preprocessing. The following example
illustrates the use of the EXTERN keyword:
EXEC SQL
SET DATABASE EMP = EXTERN ’employee.gdb’;
If an application contains an EXTERN reference, then when it is used at run time, the
actual SET DATABASE declaration must be processed first, and the database connected
before other modules can access it.
A single SET DATABASE statement can contain either the STATIC or EXTERN keyword, but not
both. A scope declaration in SET DATABASE applies to both
COMPILETIME and RUNTIME databases.
40 INTERBASE 6
OPENING A DATABASE
For more information about character sets, see the Data Definition Guide. For the
complete syntax of SET NAMES and CONNECT, see the Language Reference.
Opening a database
After a database is declared, it must be attached with a CONNECT statement before it can
be used. CONNECT:
g Allocates system resources for the database.
g Determines if the database file is local, residing on the same host where the application
itself is running, or remote, residing on a different host.
g Opens the database and examines it to make sure it is valid.
InterBase provides transparent access to all databases, whether local or remote. If the
database structure is invalid, the on-disk structure (ODS) number does not correspond to
the one required by InterBase, or if the database is corrupt, InterBase reports an error,
and permits no further access.
Optionally, CONNECT can be used to specify:
g A user name and password combination that is checked against the server’s security
database before allowing the connect to succeed. User names can be up to 31 characters.
Passwords are restricted to 8 characters.
g An SQL role name that the user adopts on connection to the database, provided that the
user has previously been granted membership in the role. Regardless of role
memberships granted, the user belongs to no role unless specified with this ROLE clause.
The client can specify at most one role per connection, and cannot switch roles except
by reconnecting.
g The size of the database buffer cache to allocate to the application when the default cache
size is inappropriate.
g Host-language variable.
g Hard-coded file name.
42 INTERBASE 6
OPENING A DATABASE
gets(fname);
. . .
EXEC SQL
CONNECT :fname;
. . .
Tip This technique is especially useful for programs that are designed to work with many
identically structured databases, one at a time, such as CAD/CAM or architectural
databases.
In this example, SET DATABASE provides a hard-coded database file name for
preprocessing with gpre. When a user runs the program, the database specified in the
variable, fname, is used instead.
host is required only if a program and a database file it uses reside on different nodes.
Similarly, path is required only if the database file does not reside in the current working
directory. For example, the following CONNECT statement contains a hard-coded file name
that includes both a Unix host name and a path name:
EXEC SQL
CONNECT ’valdez:usr/interbase/examples/employee.gdb’;
IMPORTANT A program that accesses multiple databases cannot use this form of CONNECT.
IN MULTI-DATABASE PROGRAMS
A program that accesses multiple databases must declare handles for each of them in
separate SET DATABASE statements. These handles must be used in subsequent CONNECT
statements to identify specific databases to open:
. . .
EXEC SQL
SET DATABASE DB1 = ’employee.gdb’;
EXEC SQL
SET DATABASE DB2 = ’employee2.gdb’;
EXEC SQL
CONNECT DB1;
EXEC SQL
CONNECT DB2;
. . .
Later, when the program closes these databases, the database handles are no longer in
use. These handles can be reassigned to other databases by hard-coding a file name in a
subsequent CONNECT statement. For example,
44 INTERBASE 6
OPENING A DATABASE
. . .
EXEC SQL
DISCONNECT DB1, DB2;
EXEC SQL
CONNECT ’project.gdb’ AS DB1;
. . .
Single Multiple
Syntax Description Example access access
CONNECT ‘dbfile’; Opens a single, hard-coded database file, EXEC SQL Yes No
dbfile. CONNECT ‘employee.gdb’;
CONNECT handle; Opens the database file associated with a EXEC SQL Yes Yes
previously declared database handle. This is CONNECT EMP;
the preferred CONNECT syntax.
CONNECT ‘dbfile’ AS Opens a hard-coded database file, dbfile, and EXEC SQL Yes Yes
handle; assigns a previously declared database handle CONNECT ‘employee.gdb’
to it. AS EMP;
CONNECT :varname AS Opens the database file stored in the EXEC SQL Yes Yes
handle; host-language variable, varname, and assigns a CONNECT :fname AS EMP;
previously declared database handle to it.
TABLE 3.1 CONNECT syntax summary
For a complete discussion of CONNECT syntax and its uses, see the Language Reference.
EXEC SQL
CONNECT DEFAULT;
CONNECT can also attach to a specified list of databases. Separate each database request
from others with commas. For example, the following statement opens two databases
specified by their handles:
EXEC SQL
CONNECT DB1, DB2;
The next statement opens two hard-coded database files and also assigns them to
previously declared handles:
EXEC SQL
CONNECT ’employee.gdb’ AS DB1, ’employee2.gdb’ AS DB2;
Tip Opening multiple databases with a single CONNECT is most effective when a program’s
database access is simple and clear. In complex programs that open and close several
databases, that substitute database names with host-language variables, or that assign
multiple handles to the same database, use separate CONNECT statements to make
program code easier to read, debug, and modify.
46 INTERBASE 6
OPENING A DATABASE
:error_exit
isc_print_sqlerr(sqlcode, status_vector);
EXEC SQL
DISCONNECT ALL;
exit(1);
. . .
For a complete discussion of SQL error handling, see Chapter 12, “Error Handling and
Recovery.”
Note If you specify a buffer size that is less than the smallest one currently in use for the
database, the request is ignored.
The next statement opens two databases, TEST and EMP. Because CACHE is not specified
for TEST, its buffers default to 256. EMP is opened with the CACHE clause specifying 400
buffers:
EXEC SQL
CONNECT TEST, EMP CACHE 400;
The same effect can be achieved by specifying the same amount of cache for individual
databases:
. . .
EXEC SQL
CONNECT EMP CACHE 400, TEST CACHE 400;
. . .
48 INTERBASE 6
DIFFERENTIATING TABLE NAMES
For example, the following cursor declaration accesses an EMPLOYEE table in TEST, and
another EMPLOYEE table in EMP. TEST and EMP are used as prefixes to indicate which
EMPLOYEE table should be referenced:
. . .
EXEC SQL
DECLARE IDMATCH CURSOR FOR
SELECT TESTNO INTO :matchid FROM TEST.EMPLOYEE
WHERE (SELECT EMPNO FROM EMP.EMPLOYEE WHERE EMPNO = TESTNO);
. . .
Note DSQL does not support access to multiple databases in a single statement.
Closing a database
When a program is finished with a database, the database should be closed. In SQL, a
database can be closed in either of the following ways:
g Issue a DISCONNECT to detach a database and close files.
g Append a RELEASE option to a COMMIT or ROLLBACK to disconnect from a database and
close files.
DISCONNECT, COMMIT RELEASE, and ROLLBACK RELEASE perform the following tasks:
g Close open database files.
g Disconnect from remote database connections.
g Release the memory that holds database metadata descriptions and InterBase
engine-compiled requests.
Note Closing databases with DISCONNECT is preferred for compatibility with the SQL-92
standard. Do not close a database until it is no longer needed. Once closed, a database
must be reopened, and its resources reallocated, before it can be used again.
With DISCONNECT
To close all open databases by disconnecting from them, use the following DISCONNECT
syntax:
EXEC SQL
DISCONNECT {ALL | DEFAULT};
For example, each of the following statements closes all open databases in a
program:
EXEC SQL
DISCONNECT ALL;
EXEC SQL
DISCONNECT DEFAULT;
Note A database should not be closed until all transactions are finished with it, or it must
be reopened and its resources reallocated.
To close specific databases, provide their handles as parameters following the RELEASE
option with COMMIT or ROLLBACK, using the following syntax:
EXEC SQL
COMMIT | ROLLBACK RELEASE handle [, handle ...];
50 INTERBASE 6
CLOSING A DATABASE
52 INTERBASE 6
CHAPTER
Working with
Chapter4
4
Transactions
All SQL data definition and data manipulation statements take place within the context
of a transaction, a set of SQL statements that works to carry out a single task. This chapter
explains how to open, control, and close transactions using the following SQL transaction
management statements:
Statement Purpose
SET TRANSACTION Starts a transaction, assigns it a name, and specifies its behavior. The following
behaviors can be specified:
Access mode describes the actions a transaction’s statements can perform.
Lock resolution describes how a transaction should react if a lock conflict occurs.
Isolation level describes the view of the database given a transaction as it relates to
actions performed by other simultaneously occurring transactions.
Table reservation, an optional list of tables to lock for access at the start of the
transaction rather than at the time of explicit reads or writes.
Database specification, an optional list limiting the open databases to which a
transaction may have access.
COMMIT Saves a transaction’s changes to the database and ends the transaction.
ROLLBACK Undoes a transaction’s changes before they have been committed to the database,
and ends the transaction.
TABLE 4.1 SQL transaction management statements
54 INTERBASE 6
STARTING THE DEFAULT TRANSACTION
For more information about gpre, see Chapter 14, “Preprocessing, Compiling,
and Linking.” For more information about transaction behavior, see “Specifying SET
TRANSACTION behavior” on page 60.
The default transaction is especially useful for programs that use only a single
transaction. It is automatically started in programs that require a transaction context
where none is explicitly provided. It can also be explicitly started in a program with SET
TRANSACTION.
To learn more about transaction behavior, see “Starting the default transaction” on
page 55.
A programmer need only start the default transaction explicitly in a single transaction
program to modify its operating characteristics or when writing a DSQL application that
is preprocessed with the gpre -m switch.
During preprocessing, when gpre encounters a statement, such as SELECT, that requires a
transaction context without first finding a SET TRANSACTION statement, it automatically
generates a default transaction as long as the -m switch is not specified. A default
transaction started by gpre uses a predefined, or default, behavior that dictates how the
transaction interacts with other simultaneous transactions attempting to access the same
data.
IMPORTANT DSQL programs should be preprocessed with the gpre -m switch if they start a transaction
through DSQL. In this mode, gpre does not generate the default transaction as needed,
but instead reports an error if there is no transaction.
For more information about transaction behaviors that can be modified, see “Specifying
SET TRANSACTION behavior” on page 60. For more information about using the gpre
-m switch, see Chapter 14, “Preprocessing, Compiling, and Linking.”
Note Explicitly starting the default transaction is good programming practice. It makes
a program’s source code easier to understand.
The following statements are equivalent. They both start the default transaction with the
default behavior.
EXEC SQL
SET TRANSACTION;
EXEC SQL
SET TRANSACTION NAME gds__trans READ WRITE WAIT ISOLATION LEVEL
SNAPSHOT;
56 INTERBASE 6
STARTING A NAMED TRANSACTION
To start the default transaction, but change its characteristics, SET TRANSACTION must be
used to specify those characteristics that differ from the default. Characteristics that do
not differ from the default can be omitted. For example, the following statement starts
the default transaction for READ ONLY access, WAIT lock resolution, and ISOLATION LEVEL
SNAPSHOT:
EXEC SQL
SET TRANSACTION READ ONLY;
As this example illustrates, the NAME clause can be omitted when starting the default
transaction.
IMPORTANT In DSQL, changing the characteristics of the default transaction is accomplished as with
PREPARE and EXECUTE in a manner similar to the one described, but the program must
be preprocessed using the gpre -m switch.
For more information about preprocessing programs with the -m switch, see Chapter 14,
“Preprocessing, Compiling, and Linking.” For more information about transaction
behavior and modification, see “Specifying SET TRANSACTION behavior” on page 60.
IMPORTANT Using named transactions in dynamic SQL statements is somewhat different. For
information about named transactions in DSQL, see “Working with multiple
transactions in DSQL” on page 83.
For additional information about creating multiple transaction programs, see “Working
with multiple transactions” on page 79.
Naming transactions
A transaction name is a programmer-supplied variable that distinguishes one transaction
from another in SQL statements. If transaction names are not used in SQL statements that
control transactions and manipulate data, then those statements operate only on the
default transaction, GDS__TRANS.
The following C code declares and initializes two transaction names using the
isc_tr_handle datatype. It then starts those transactions in SET TRANSACTION statements.
. . .
EXEC SQL
BEGIN DECLARE SECTION;
isc_tr_handle t1, t2; /* declare transaction names */
EXEC SQL
END DECLARE SECTION;
. . .
t1 = t2 = (isc_tr_handle) NULL; /* initialize names to zero */
. . .
EXEC SQL
SET TRANSACTION NAME t1; /* start trans. w. default behavior */
EXEC SQL
SET TRANSACTION NAME t2; /* start trans2. w. default behavior */
. . .
58 INTERBASE 6
STARTING A NAMED TRANSACTION
Note In this example, the transaction declaration occurs within an SQL section
declaration. While InterBase does not require that host-language variables occur within
a section declaration, putting them there guarantees compatibility with other SQL
implementations that do require section declarations.
Transaction names are usually declared globally at the module level. If a transaction
name is declared locally, ensure that:
g The transaction using the name is completely contained within the function where the
name is declared. Include an error-handling routine to roll back transactions when errors
occur. ROLLBACK releases a transaction name, and sets its value to NULL.
g The transaction name is not used outside the function where it is declared.
To reference a transaction name declared in another module, provide an external
declaration for it. For example, in C, the external declaration for t1 and t2 might be as
follows:
EXEC SQL
BEGIN DECLARE SECTION;
extern isc_tr_handle t1, t2;
EXEC SQL
END DECLARE SECTION;
For a summary of the default behavior for a transaction started without specifying
behavior parameters, see table 4.2 on page 56. The following statements are equivalent:
they both start the transaction named t1, using default transaction behavior.
EXEC SQL
SET TRANSACTION NAME t1;
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE WAIT ISOLATION LEVEL SNAPSHOT;
60 INTERBASE 6
STARTING A NAMED TRANSACTION
The following table lists the optional SET TRANSACTION parameters for specifying the
behavior of the default transaction:
4 Access mode
The access mode parameter specifies the type of access a transaction has for the tables it
uses. There are two possible settings:
g READ ONLY specifies that a transaction can select data from a table, but cannot insert,
update, or delete table data.
g READ WRITE specifies that a transaction can select, insert, update, and delete table data.
This is the default setting if none is specified.
InterBase assumes that most transactions both read and write data. When starting a
transaction for reading and writing, READ WRITE can be omitted from SET TRANSACTION
statement. For example, the following statements start a transaction, t1, for READ WRITE
access:
EXEC SQL
SET TRANSACTION NAME t1;
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE;
Tip It is good programming practice to specify a transaction’s access mode, even when it is
READ WRITE. It makes an application’s source code easier to read and debug because the
program’s intentions are clearly spelled out.
Start a transaction for READ ONLY access when you only need to read data. READ ONLY
must be specified. For example, the following statement starts a transaction, t1, for
read-only access:
EXEC SQL
SET TRANSACTION NAME t1 READ ONLY;
62 INTERBASE 6
STARTING A NAMED TRANSACTION
4 Isolation level
The isolation level parameter specifies the control a transaction exercises over table
access. It determines the:
g View of a database the transaction can see.
g Table access allowed to this and other simultaneous transactions.
The following table describes the three isolation levels supported by InterBase:
The isolation level for most transactions should be either SNAPSHOT or READ COMMITTED.
These levels enable simultaneous transactions to select, insert, update, and delete data in
shared databases, and they minimize the chance for lock conflicts. Lock conflicts occur
in two situations:
g When a transaction attempts to update a row already updated or deleted by another
transaction. A row updated by a transaction is effectively locked for update to all other
transactions until the controlling transaction commits or rolls back. READ COMMITTED
transactions can read and update rows updated by simultaneous transactions after they
commit.
g When a transaction attempts to insert, update, or delete a row in a table locked by another
transaction with an isolation level of SNAPSHOT TABLE STABILITY. SNAPSHOT TABLE STABILITY
locks entire tables for write access, although concurrent reads by other SNAPSHOT and
READ COMMITTED transactions are permitted.
Using SNAPSHOT TABLE STABILITY guarantees that only a single transaction can make
changes to tables, but increases the chance of lock conflicts where there are simultaneous
transactions attempting to access the same tables. For more information about the
likelihood of lock conflicts, see “Isolation level interactions” on page 68.
64 INTERBASE 6
STARTING A NAMED TRANSACTION
Except as noted, all three InterBase isolation levels control these problems. The following
table summarizes how a transaction with a particular isolation level controls access to its
data for other simultaneous transactions:
Lost updates Other transactions cannot update rows Other transactions cannot update tables
already updated by this transaction. controlled by this transaction.
Dirty reads Other SNAPSHOT transactions can only read a Other transactions cannot access tables
previous version of a row updated by this updated by this transaction.
transaction.
Other READ COMMITTED transactions can only
read a previous version, or committed
updates.
Non-reproducible SNAPSHOT and SNAPSHOT TABLE STABILITY SNAPSHOT and SNAPSHOT TABLE STABILITY
reads transactions can only read versions of rows transactions can only read versions of rows
committed when they started. committed when they started.
READ COMMITTED transactions must expect that Other transactions cannot access tables
reads cannot be reproduced. updated by this transaction.
Phantom rows READ COMMITTED transactions may encounter Other transactions cannot access tables
phantom rows. controlled by this transaction.
Update side effects Other SNAPSHOT transactions can only read a Other transactions cannot update tables
previous version of a row updated by this controlled by this transaction.
transaction. Use triggers and integrity constraints to avoid
Other READ COMMITTED transactions can only any problems with interleaved transactions.
read a previous version, or committed
updates.
Use triggers and integrity constraints to try to
avoid any problems with interleaved
transactions.
TABLE 4.5 InterBase management of classic transaction conflicts
SNAPSHOT transactions receive a stable view of a database as it exists the moment the
transactions start. READ COMMITTED transactions can see the latest committed versions of
rows. Both types of transactions can use SELECT statements unless they encounter the
following conditions:
g Table locked by SNAPSHOT TABLE STABILITY transaction for UPDATE.
g Uncommitted inserts made by other simultaneous transactions. In this case, a SELECT is
allowed, but changes cannot be seen.
READ COMMITTED transactions can read the latest committed version of rows. A SNAPSHOT
transaction can read only a prior version of the row as it existed before the update
occurred.
SNAPHOT and READ COMMITTED transactions with READ WRITE access can use INSERT,
UPDATE, and DELETE unless they encounter tables locked by SNAPSHOT TABLE STABILITY
transactions.
SNAPSHOT transactions cannot update or delete rows previously updated or deleted and
then committed by other simultaneous transactions. Attempting to update a row
previously updated or deleted by another transaction results in an update conflict error.
A READ COMMITTED READ WRITE transaction can read changes committed by other
transactions, and subsequently update those changed rows.
Occasional update conflicts may occur when simultaneous SNAPSHOT and READ
COMMITTED transactions attempt to update the same row at the same time. When update
conflicts occur, expect the following behavior:
g For mass or searched updates, updates where a single UPDATE modifies multiple rows in
a table, all updates are undone on conflict. The UPDATE can be retried. For READ
COMMITTED transactions, the NO RECORD_VERSION option can be used to narrow the
window between reads and updates or deletes. For more information, see “Starting a
transaction with READ COMMITTED isolation level” on page 67.
g For cursor or positioned updates, where rows are retrieved and updated from an active
set one row at a time, only a single update is undone. To retry the update, the cursor must
be closed, then reopened, and updates resumed at the point of previous conflict.
For more information about UPDATE through cursors, see Chapter 6, “Working with
Data.”
66 INTERBASE 6
STARTING A NAMED TRANSACTION
EXEC SQL
SET TRANSACTION NAME t1;
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE SNAPSHOT;
When an isolation level is specified, it must follow the access and lock resolution modes.
Tip It is good programming practice to specify a transaction’s isolation level, even when it is
SNAPSHOT. It makes an application’s source code easier to read and debug because the
program’s intentions are clearly spelled out.
Isolation level always follows access mode. If the access mode is omitted, isolation level
is the first parameter to follow the transaction name.
READ COMMITTED supports mutually exclusive optional parameters, RECORD_VERSION and
NO RECORD_VERSION, which determine the READ COMMITTED behavior when it encounters
a row where the latest version of that row is uncommitted:
g RECORD_VERSION specifies that the transaction immediately reads the latest committed
version of a row, even if a more recent uncommitted version also resides on disk.
g NO RECORD_VERSION, the default, specifies that the transaction can only read the latest
version of a requested row. If the WAIT lock resolution option is also specified, then the
transaction waits until the latest version of a row is committed or rolled back, and retries
its read. If the NO WAIT option is specified, the transaction returns an immediate
deadlock error.
Because NO RECORD_VERSION is the default behavior, it need not be specified with READ
COMITTED. For example, the following statements are equivalent. They start a named
transaction, t1, for READ WRITE access and set isolation level to READ COMMITTED NO
RECORD_VERSION.
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE READ COMMITTED;
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE READ COMMITTED
NO RECORD_VERSION;
RECORD_VERSION must always be specified when it is used. For example, the following
statement starts a named transaction, t1, for READ WRITE access and sets isolation level to
READ COMMITTED RECORD_VERSION:
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE READ COMMITTED
RECORD_VERSION;
Isolation level always follows the optional access mode and lock resolution parameters,
if they are present.
IMPORTANT Use SNAPSHOT TABLE STABILITY with care. In an environment where multiple transactions
share database access, SNAPSHOT TABLE STABILITY greatly increases the likelihood of lock
conflicts.
68 INTERBASE 6
STARTING A NAMED TRANSACTION
As this table illustrates, SNAPSHOT and READ COMMITTED transactions offer the least
chance for conflicts. For example, if t1 is a SNAPSHOT transaction with READ WRITE
access, and t2 is a READ COMMITTED transaction with READ WRITE access, t1 and t2 only
conflict when they attempt to update the same rows. If t1 and t2 have READ ONLY access,
they never conflict with any other transaction.
A SNAPSHOT TABLE STABILITY transaction with READ WRITE access is guaranteed that it
alone can update tables, but it conflicts with all other simultaneous transactions except
for SNAPSHOT and READ COMMITTED transactions running in READ ONLY mode. A SNAPSHOT
TABLE STABILITY transaction with READ ONLY access is compatible with any other read-only
transaction, but conflicts with any transaction that attempts to insert, update, or delete
data.
4 Lock resolution
The lock resolution parameter determines what happens when a transaction encounters
a lock conflict. There are two options:
g WAIT, the default, causes the transaction to wait until locked resources are released. Once
the locks are released, the transaction retries its operation.
g NO WAIT returns a lock conflict error without waiting for locks to be released.
Because WAIT is the default lock resolution, you don’t need to specify it in a SET
TRANSACTION statement. For example, the following statements are equivalent. They both
start a transaction, t1, for READ WRITE access, WAIT lock resolution, and READ COMMITTED
isolation level:
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE READ COMMITTED;
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE WAIT READ COMMITTED;
To use NO WAIT, the lock resolution parameter must be specified. For example, the
following statement starts the named transaction, t1, for READ WRITE access, NO WAIT lock
resolution, and SNAPSHOT isolation level:
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE NO WAIT READ SNAPSHOT;
When lock resolution is specified, it follows the optional access mode, and precedes the
optional isolation level parameter.
Tip It is good programming practice to specify a transaction’s lock resolution, even when it
is WAIT. It makes an application’s source code easier to read and debug because the
program’s intentions are clearly spelled out.
4 RESERVING clause
The optional RESERVING clause enables transactions to guarantee themselves specific
levels of access to a subset of available tables at the expense of other simultaneous
transactions. Reservation takes place at the start of the transaction instead of only when
data manipulation statements require a particular level of access. RESERVING is only useful
in an environment where simultaneous transactions share database access. It has three
main purposes:
g To prevent possible deadlocks and update conflicts that can occur if locks are taken only
when actually needed (the default behavior).
g To provide for dependency locking, the locking of tables that may be affected by triggers
and integrity constraints. While explicit dependency locking is not required, it can assure
that update conflicts do not occur because of indirect table conflicts.
g To change the level of shared access for one or more individual tables in a transaction.
For example, a READ WRITE SNAPSHOT transaction may need exclusive update rights for a
single table, and could use the RESERVING clause to guarantee itself sole write access to
the table.
IMPORTANT A single SET TRANSACTION statement can contain either a RESERVING or a USING clause,
but not both. Use the SET TRANSACTION syntax to reserve tables for a transaction:
EXEC SQL
SET TRANSACTION [NAME name]
[READ WRITE| READ ONLY]
[WAIT | NO WAIT]
[[ISOLATION LEVEL] {SNAPSHOT [TABLE STABILITY]
| READ COMMITTED [[NO] RECORD_VERSION]}]
RESERVING <reserving_clause>;
70 INTERBASE 6
STARTING A NAMED TRANSACTION
Each table should only appear once in the RESERVING clause. Each table, or a list of tables
separated by commas, must be followed by a clause describing the type of reservation
requested. The following table lists these reservation options:
Reservation
option Purpose
PROTECTED READ Prevents other transactions from updating rows. All transactions can select
from the table.
PROTECTED WRITE Prevents other transactions from updating rows.
SNAPSHOT and READ COMMITTED transactions can select from the table, but only
this transaction can update rows.
SHARED READ Any transaction can select from this table. Any READ WRITE transaction can
update this table. This is the most liberal reservation mode.
SHARED WRITE Any SNAPSHOT or READ COMMITTED READ WRITE transaction can update this table.
Other SNAPSHOT and READ COMMITTED transactions can also select from this
table.
TABLE 4.7 Table reservation options for the RESERVING clause
The following statement starts a SNAPSHOT transaction, t1, for READ WRITE access, and
reserves a single table for PROTECTED WRITE access:
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE WAIT SNAPSHOT
RESERVING EMPLOYEE FOR PROTECTED WRITE;
The next statement starts a READ COMMITTED transaction, t1, for READ WRITE access, and
reserves two tables, one for SHARED WRITE, and another for PROTECTED READ:
EXEC SQL
SET TRANSACTION NAME t1 READ WRITE WAIT READ COMMITTED
RESERVING EMPLOYEES FOR SHARED WRITE, EMP_PROJ
FOR PROTECTED READ;
SNAPSHOT and READ COMMITTED transactions use RESERVING to implement more restrictive
access to tables for other simultaneous transactions. SNAPSHOT TABLE STABILITY
transactions use RESERVING to reduce the likelihood of deadlock in critical situations.
4 USING clause
Every time a transaction is started, InterBase reserves system resources for each database
currently attached for program access. In a multi-transaction, multi-database program,
the USING clause can be used to preserve system resources by restricting the number of
open databases to which a transaction has access. USING restricts a transaction’s access
to tables to a listed subset of all open databases using the following syntax:
EXEC SQL
SET TRANSACTION [NAME name]
[READ WRITE | READ ONLY]
[WAIT | NO WAIT]
[[ISOLATION LEVEL] {SNAPSHOT [TABLE STABILITY]
| READ COMMITTED [[NO] RECORD_VERSION]}]
USING dbhandle> [, dbhandle ...];
IMPORTANT A single SET TRANSACTION statement can contain either a USING or a RESERVING clause,
but not both.
The following C program fragment opens three databases, test.gdb, research.gdb, and
employee.gdb, assigning them to the database handles TEST, RESEARCH, and EMP,
respectively. Then it starts the default transaction and restricts its access to TEST and EMP:
. . .
EXEC SQL
SET DATABASE ATLAS = ’test.gdb’;
EXEC SQL
SET DATABASE RESEARCH = ’research.gdb’;
EXEC SQL
SET DATABASE EMP = ’employee.gdb’;
EXEC SQL
CONNECT TEST, RESEARCH, EMP; /* Open all databases */
EXEC SQL
SET TRANSACTION USING TEST, EMP;
. . .
72 INTERBASE 6
USING TRANSACTION NAMES IN DATA STATEMENTS
. . .
EXEC SQL
BEGIN DECLARE SECTION;
long *mytrans1, *mytrans2;
char city[26];
EXEC SQL
END DECLARE SECTION;
mytrans1 = 0L;
mytrans2 = 0L;
. . .
EXEC SQL
SET DATABASE ATLAS = ’atlas.gdb’;
EXEC SQL
CONNECT;
EXEC SQL
DECLARE CITYLIST CURSOR FOR
SELECT CITY FROM CITIES
WHERE COUNTRY = ’Mexico’;
EXEC SQL
SET TRANSACTION NAME mytrans1;
EXEC SQL
SET TRANSACTION mytrans2 READ ONLY READ COMMITTED;
. . .
printf(’Mexican city to add to database: ’);
gets(city);
EXEC SQL
INSERT TRANSACTION mytrans1 INTO CITIES (CITY, COUNTRY)
VALUES :city, ’Mexico’;
EXEC SQL
COMMIT mytrans1;
EXEC SQL
OPEN TRANSACTION mytrans2 CITYLIST;
EXEC SQL
FETCH CITYLIST INTO :city;
while (!SQLCODE)
{
printf("%s\n", city);
EXEC SQL
FETCH CITYLIST INTO :city;
}
EXEC SQL
CLOSE CITYLIST;
EXEC SQL
COMMIT;
EXEC SQL
DISCONNECT;
. . .
Note The DSQL EXECUTE and EXECUTE IMMEDIATE statements also support transaction
names.
For more information about using transaction names with data manipulation statements,
see Chapter 6, “Working with Data.” For more information about transaction names
and the COMMIT statement, see “Using COMMIT” on page 75. For more information
about using transaction names with DSQL statements, see “Working with multiple
transactions in DSQL” on page 83.
Ending a transaction
When a transaction’s tasks are complete, or an error prevents a transaction from
completing, the transaction must be ended to set the database to a consistent state. There
are two statements that end transactions:
g COMMIT makes a transaction’s changes permanent in the database. It signals that a
transaction completed all its actions successfully.
g ROLLBACK undoes a transaction’s changes, returning the database to its previous state,
before the transaction started. ROLLBACK is typically used when one or more errors occur
that prevent a transaction from completing successfully.
Both COMMIT and ROLLBACK close the record streams associated with the transaction,
reinitialize the transaction name to zero, and release system resources allocated for the
transaction. Freed system resources are available for subsequent use by any application
or program.
COMMIT and ROLLBACK have additional benefits. They clearly indicate program logic and
intention, make a program easier to understand, and most importantly, assure that a
transaction’s changes are handled as intended by the programmer.
74 INTERBASE 6
ENDING A TRANSACTION
IMPORTANT If the program ends before a transaction ends, a transaction is automatically rolled back,
but databases are not closed. If a program ends without closing the database, data loss
or corruption is possible. Therefore, open databases should always be closed by issuing
explicit DISCONNECT, COMMIT RELEASE, or ROLLBACK RELEASE statements.
For more information about DISCONNECT, COMMIT RELEASE, and ROLLBACK RELEASE, see
Chapter 3, “Working with Databases.”
Using COMMIT
Use COMMIT to write transaction changes permanently to a database.
COMMIT closes the record streams associated with the transaction, resets the transaction
name to zero, and frees system resources assigned to the transaction for other uses. The
complete syntax for COMMIT is:
EXEC SQL
COMMIT [TRANSACTION name] [RETAIN [SNAPSHOT] | RELEASE dbhandle
[, dbhandle ...]]
For example, the following C code fragment contains a complete transaction. It gives all
employees who have worked since December 31, 1992, a 4.3% cost-of-living salary
increase. If all qualified employee records are successfully updated, the transaction is
committed, and the changes are actually applied to the database.
. . .
EXEC SQL
SET TRANSACTION SNAPSHOT TABLE STABILITY;
EXEC SQL
UPDATE EMPLOYEE
SET SALARY = SALARY * 1.043
WHERE HIRE_DATE < ’1-JAN-1993’;
EXEC SQL
COMMIT;
. . .
By default, COMMIT affects only the default transaction, GDS__TRANS. To commit another
transaction, use its transaction name as a parameter to COMMIT.
Tip Even READ ONLY transactions that do not change a database should be ended with a
COMMIT rather than ROLLBACK. The database is not changed, but the overhead required
to start subsequent transactions is greatly reduced.
IMPORTANT In multi-transaction programs, transaction names must always be specified for COMMIT
except when committing the default transaction.
76 INTERBASE 6
ENDING A TRANSACTION
Tip Developers who use Borland tools such as Delphi use this feature by specifying “soft
commits” in the BDE configuration.
For example, the following C code fragment updates the POPULATION column by
user-specified amounts for cities in the CITIES table that are in a country also specified by
the user. Each time a qualified row is updated, a COMMIT with the RETAIN option is issued,
preserving the current cursor status and system resources.
. . .
EXEC SQL
BEGIN DECLARE SECTION;
char country[26], city[26], asciimult[10];
int multiplier;
long pop;
EXEC SQL
END DECLARE SECTION;
. . .
main ()
{
EXEC SQL
DECLARE CHANGEPOP CURSOR FOR
SELECT CITY, POPULATION
FROM CITIES
WHERE COUNTRY = :country;
printf("Enter country with city populations needing adjustment: ");
gets(country);
EXEC SQL
SET TRANSACTION;
EXEC SQL
OPEN CHANGEPOP;
EXEC SQL
FETCH CHANGEPOP INTO :city, :pop;
while(!SQLCODE)
{
printf("City: %s Population: %ld\n", city, pop);
printf("\nPercent change (100%% to -100%%:");
gets(asciimult);
multiplier = atoi(asciimult);
EXEC SQL
UPDATE CITIES
SET POPULATION = POPULATION * (1 + :multiplier / 100)
WHERE CURRENT OF CHANGEPOP;
EXEC SQL
COMMIT RETAIN; /* commit changes, save current state */
EXEC SQL
FETCH CHANGEPOP INTO :city, :pop;
if (SQLCODE && (SQLCODE != 100))
{
isc_print_sqlerror(SQLCODE, isc_$status);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT;
exit(1);
}
}
EXEC SQL
COMMIT;
EXEC SQL
DISCONNECT;
}
Note If you execute a ROLLBACK after a COMMIT RETAIN, it rolls back only updates and
writes that occurred after the COMMIT RETAIN.
IMPORTANT In multi-transaction programs, a transaction name must be specified for COMMIT RETAIN,
except when retaining the state of the default transaction. For more information about
transaction names, see “Naming transactions” on page 58.
Using ROLLBACK
Use ROLLBACK to restore the database to its condition prior to the start of the transaction.
ROLLBACK also closes the record streams associated with the transaction, resets the
transaction name to zero, and frees system resources assigned to the transaction for other
uses. ROLLBACK typically appears in error-handling routines. The syntax for ROLLBACK is:
EXEC SQL
ROLLBACK [TRANSACTION name] [RELEASE [dbhandle [, dbhandle ...]]];
78 INTERBASE 6
WORKING WITH MULTIPLE TRANSACTIONS
For example, the following C code fragment contains a complete transaction that gives
all employees who have worked since December 31, 1992, a 4.3% cost-of-living salary
adjustment. If all qualified employee records are successfully updated, the transaction is
committed, and the changes are actually applied to the database. If an error occurs, all
changes made by the transaction are undone, and the database is restored to its condition
prior to the start of the transaction.
. . .
EXEC SQL
SET TRANSACTION SNAPSHOT TABLE STABILITY;
EXEC SQL
UPDATE EMPLOYEES
SET SALARY = SALARY * 1.043
WHERE HIRE_DATE < ’1-JAN-1993’;
if (SQLCODE && (SQLCODE != 100))
{
isc_print_sqlerror(SQLCODE, isc_$status);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT;
exit(1);
}
EXEC SQL
COMMIT;
EXEC SQL
DISCONNECT;
. . .
By default, ROLLBACK affects only the default transaction, GDS__TRANS. To roll back other
transactions, use their transaction names as parameters to
ROLLBACK.
IMPORTANT DSQL programs must be preprocessed with the gpre -m switch. In this mode, gpre does
not generate the default transaction automatically, but instead reports an error. DSQL
programs require that all transactions be explicitly started.
Using cursors
DECLARE CURSOR does not support transaction names. Instead, to associate a named
transaction with a cursor, include the transaction name as an optional parameter in the
cursor’s OPEN statement. A cursor can only be associated with a single transaction. For
example, the following statements declare a cursor, and open it, associating it with the
transaction, T1:
. . .
EXEC SQL
DECLARE S CURSOR FOR
SELECT COUNTRY, CUST_NO, SUM(QTY_ORDERED)
FROM SALES
80 INTERBASE 6
WORKING WITH MULTIPLE TRANSACTIONS
GROUP BY CUST_NO
WHERE COUNTRY = ’Mexico’;
EXEC SQL
SET TRANSACTION T1 READ ONLY READ COMMITTED;
. . .
EXEC SQL
OPEN TRANSACTION T1 S;
. . .
An OPEN statement without the optional transaction name parameter operates under
control of the default transaction, GDS__TRANS.
Once a named transaction is associated with a cursor, subsequent cursor statements
automatically operate under control of that transaction. Therefore, it does not support a
transaction name parameter. For example, the following statements illustrate a FETCH and
CLOSE for the S cursor after it is associated with the named transaction, t2:
. . .
EXEC SQL
OPEN TRANSACTION t2 S;
EXEC SQL
FETCH S INTO :country, :cust_no, :qty;
while (!SQLCODE)
{
printf("%s %d %d\n", country, cust_no, qty);
EXEC SQL
FETCH S INTO :country, :cust_no, :qty;
}
EXEC SQL
CLOSE S;
. . .
Multiple cursors can be controlled by a single transaction, or each transaction can control
a single cursor according to a program’s needs.
A multi-transaction example
The following C code illustrates the steps required to create a simple multi-transaction
program. It declares two transaction handles, mytrans1, and mytrans2, initializes them
to zero, starts the transactions, and then uses the transaction names to qualify the data
manipulation statements that follow. It also illustrates the use of a cursor with a named
transaction.
. . .
EXEC SQL
BEGIN DECLARE SECTION;
long *mytrans1 = 0L, *mytrans2 = 0L;
char city[26];
EXEC SQL
END DECLARE SECTION;
. . .
EXEC SQL
DECLARE CITYLIST CURSOR FOR
SELECT CITY FROM CITIES
WHERE COUNTRY = ’Mexico’;
EXEC SQL
SET TRANSACTION NAME mytrans1;
EXEC SQL
SET TRANSACTION mytrans2 READ ONLY READ COMMITTED;
. . .
printf("Mexican city to add to database: ");
gets(city);
EXEC SQL
INSERT TRANSACTION mytrans1 INTO CITIES
VALUES :city, ’Mexico’, NULL, NULL, NULL, NULL;
EXEC SQL
COMMIT mytrans1;
EXEC SQL
OPEN TRANSACTION mytrans2 CITYLIST;
EXEC SQL
FETCH CITYLIST INTO :city;
while (!SQLCODE)
{
printf("%s\n", city);
EXEC SQL
FETCH CITYLIST INTO :city;
}
EXEC SQL
CLOSE CITYLIST;
EXEC SQL
COMMIT mytrans2;
EXEC SQL
DISCONNECT
. . .
82 INTERBASE 6
WORKING WITH MULTIPLE TRANSACTIONS IN DSQL
PREPARE
g Checks the statement in the variable for errors
g Loads the statement into an XSQLDA for a subsequent EXECUTE statement
EXECUTE IMMEDIATE
g Checks the statement for errors
g Loads the statement into the XSQLDA
g Executes the statement
Both EXECUTE and EXECUTE IMMEDIATE operate within the context of a
programmer-specified transaction, which can be a named transaction. If the transaction
name is omitted, these statements are controlled by the default transaction, GDS__TRANS.
You can modify the transaction behavior for an EXECUTE and EXECUTE IMMEDIATE
statement by:
g Enabling a user to enter a SET TRANSACTION statement into a host variable
g Executing the SET TRANSACTION statement before the EXECUTE or EXECUTE IMMEDIATE
whose transaction context should be modified
In this context, a SET TRANSACTION statement changes the behavior of the next named or
default transaction until another SET TRANSACTION occurs.
The following C code fragment provides the user the option of specifying a new
transaction behavior, applies the behavior change, executes the next user statement in
the context of that changed transaction, then restores the transaction’s original behavior.
. . .
EXEC SQL
BEGIN DECLARE SECTION;
char usertrans[512], query[1024];
char deftrans[] = {"SET TRANSACTION READ WRITE WAIT SNAPSHOT"};
EXEC SQL
END DECLARE SECTION;
. . .
printf("\nEnter SQL statement: ");
gets(query);
printf("\nChange transaction behavior (Y/N)? ");
gets(usertrans);
if (usertrans[0] == "Y" || usertrans[0] == "y")
{
printf("\nEnter \"SET TRANSACTION\" and desired behavior: ");
gets(usertrans);
EXEC SQL
COMMIT usertrans;
EXEC SQL
EXECUTE IMMEDIATE usertrans;
}
84 INTERBASE 6
WORKING WITH MULTIPLE TRANSACTIONS IN DSQL
else
{
EXEC SQL
EXECUTE IMMEDIATE deftrans;
}
EXEC SQL
EXECUTE IMMEDIATE query;
EXEC SQL
EXECUTE IMMEDIATE deftrans;
. . .
IMPORTANT As this example illustrates, you must commit or roll back any previous transactions
before you can execute SET TRANSACTION.
86 INTERBASE 6
CHAPTER
This chapter discusses how to create, modify, and delete databases, tables, views, and
indexes in SQL applications. A database’s tables, views, and indexes make up most of its
underlying structure, or metadata.
IMPORTANT The discussion in this chapter applies equally to dynamic SQL (DSQL) applications,
except that users enter DSQL data definition statements at run time, and do not preface
those statements with EXEC SQL.
The preferred method for creating, modifying, and deleting metadata is through the
InterBase interactive SQL tool, isql, but in some instances, it may be necessary or desirable
to embed some data definition capabilities in an SQL application. Both SQL and DSQL
applications can use the following subset of data definition statements:
DSQL also supports creating, altering, and dropping stored procedures, triggers, and
exceptions. DSQL is especially powerful for data definition because it enables users to
enter any supported data definition statement at run time. For example, isql itself is a
DSQL application. For more information about using isql to define stored procedures,
triggers, and exceptions, see the Data Definition Guide. For a complete discussion of
DSQL programming, see Chapter 13, “Using Dynamic SQL.”
Creating metadata
SQL data definition statements are used in applications the sole purpose of which is to
create or modify databases or tables. Typically the expectation is that these applications
will be used only once by any given user, then discarded, or saved for later modification
by a database designer who can read the program code as a record of a database’s
structure. If data definition changes must be made, editing a copy of existing code is
easier than starting over.
Note Use the InterBase interactive SQL tool, isql, to create and alter data definitions
whenever possible. For more information about isql, see the Operations Guide
88 INTERBASE 6
CREATING METADATA
The SQL CREATE statement is used to make new databases, domains, tables, views, or
indexes. A COMMIT statement must follow every CREATE so that subsequent CREATE
statements can use previously defined metadata upon which they may rely. For example,
domain definitions must be committed before the domain can be referenced in
subsequent table definitions.
IMPORTANT Applications that mix data definition and data manipulation must be preprocessed using
the gpre -m switch. Such applications must explicitly start every transaction with SET
TRANSACTION.
Creating a database
CREATE DATABASE establishes a new database and its system tables, tables that describe the
internal structure of the database. InterBase uses the system tables whenever an
application accesses a database. SQL programs can read the data in most of these tables
just like any user-created table.
In its most elementary form, the syntax for CREATE DATABASE is:
EXEC SQL
CREATE DATABASE ’<filespec>’;
CREATE DATABASE must appear before any other CREATE statements. It requires one
parameter, the name of a database to create. For example, the following statement creates
a database named employee.gdb:
EXEC SQL
CREATE DATABASE ’employee.gdb’;
Note The database name can include a full file specification, including both host or node
names, and a directory path to the location where the database file should be created.
For information about file specifications for a particular operating system, see the
operating system manuals.
IMPORTANT Although InterBase enables access to remote databases, you should always create a
database directly on the machine where it is to reside.
4 Optional parameters
There are optional parameters for CREATE DATABASE. For example, when an application
running on a client attempts to connect to an InterBase server in order to create a
database, it may be expected to provide USER and PASSWORD parameters before the
connection is established. Other parameters specify the database page size, the number
and size of multi-file databases, and the default character set for the database.
For a complete discussion of all CREATE DATABASE parameters, see the Data Definition
Guide. For the complete syntax of CREATE DATABASE, see the Language Reference.
IMPORTANT An application that creates a database must be preprocessed with the gpre -m switch. It
must also create at least one table. If a database is created without a table, it cannot be
successfully opened by another program. Applications that perform both data definition
and data manipulation must declare tables with DECLARE TABLE before creating and
populating them. For more information about table creation, see “Creating a table” on
page 91.
If you do not specify a character set, the character set defaults to NONE. Using character
set NONE means that there is no character set assumption for columns; data is stored and
retrieved just as you originally entered it. You can load any character set into a column
defined with NONE, but you cannot later move that data into another column that has
been defined with a different character set. In this case, no transliteration is performed
between the source and destination character sets, and errors may occur during
assignment.
For a complete description of the DEFAULT CHARACTER SET clause and a list of the character
sets supported by InterBase, see the Data Definition Guide.
Creating a domain
CREATE DOMAIN creates a column definition that is global to the database, and that can
be used to define columns in subsequent CREATE TABLE statements. CREATE DOMAIN is
especially useful when many tables in a database contain identical column definitions.
For example, in an employee database, several tables might define columns for
employees’ first and last names.
At its simplest, the syntax for CREATE DOMAIN is:
90 INTERBASE 6
CREATING METADATA
EXEC SQL
CREATE DOMAIN name AS <datatype>;
Once a domain is defined and committed, it can be used in CREATE TABLE statements to
define columns. For example, the following CREATE TABLE fragment illustrates how the
FIRSTNAME and LASTNAME domains can be used in place of column definitions in the
EMPLOYEE table definition.
EXEC SQL
CREATE TABLE EMPLOYEE
(
. . .
FIRST_NAME FIRSTNAME NOT NULL,
LAST_NAME LASTNAME NOT NULL;
. . .
);
A domain definition can also specify a default value, a NOT NULL attribute, a CHECK
constraint that limits inserts and updates to a range of values, a character set, and a
collation order.
For more information about creating domains and using them during table creation, see
the Data Definition Guide. For the complete syntax of CREATE DOMAIN, see the Language
Reference.
Creating a table
The CREATE TABLE statement defines a new database table and the columns and integrity
constraints within that table. Each column can include a character set specification and
a collation order specification. CREATE TABLE also automatically imposes a default SQL
security scheme on the table. The person who creates a table becomes its owner. A table’s
owner is assigned all privileges for it, including the right to grant privileges to other users.
A table can be created only for a database that already exists. At its simplest, the syntax
for CREATE TABLE is as follows:
EXEC SQL
CREATE TABLE name (<col_def> | <table_constraint>
[, <col_def> | <table_constraint> ...]);
An application can create multiple tables, but duplicating an existing table name is not
permitted.
For more information about SQL datatypes and integrity constraints, see the Data
Definition Guide. For more information about CREATE TABLE syntax, see the Language
Reference. For more information about changing or assigning table privileges, see the
security chapter in the Data Definition Guide.
92 INTERBASE 6
CREATING METADATA
The expression can reference previously defined columns in the table. For example, the
following statement creates a computed column, FULL_NAME, by concatenating two other
columns, LAST_NAME, and FIRST_NAME:
EXEC SQL
CREATE TABLE EMPLOYEE
(
. . .
FIRST_NAME VARCHAR(10) NOT NULL,
LAST_NAME VARCHAR(15) NOT NULL,
. . .
FULL_NAME COMPUTED BY (LAST_NAME || ’, ’ || FIRST_NAME)
);
For more information about COMPUTED BY, see the Data Definition Guide.
);
EXEC SQL
CREATE TABLE EMPLOYEE_PROJECT
(
EMP_NO SMALLINT,
PROJ_ID CHAR(5),
DUTIES Blob(240, 1)
);
EXEC SQL
COMMIT;
For more information about DECLARE TABLE, see the Language Reference.
Creating a view
A view is a virtual table that is based on a subset of one or more actual tables in a
database. Views are used to:
g Restrict user access to data by presenting only a subset of available data.
g Rearrange and present data from two or more tables in a manner especially useful to the
program.
Unlike a table, a view is not stored in the database as raw data. Instead, when a view is
created, the definition of the view is stored in the database. When a program uses the
view, InterBase reads the view definition and quickly generates the output as if it were a
table.
To make a view, use the following CREATE VIEW syntax:
EXEC SQL
CREATE VIEW name [(view_col [, view_col ...)] AS
<select> [WITH CHECK OPTION];
The name of the view, name, must be unique within the database.
To give each column displayed in the view its own name, independent of its column
name in an underlying table, enclose a list of view_col parameters in parentheses. Each
column of data returned by the view’s SELECT statement is assigned sequentially to a
corresponding view column name. If a list of view column names is omitted, column
names are assigned directly from the underlying table.
Listing independent names for columns in a view ensures that the appearance of a view
does not change if its underlying table structures are modified.
94 INTERBASE 6
CREATING METADATA
Note A view column name must be provided for each column of data returned by the
view’s SELECT statement, or else no view column names should be specified.
The select clause is a standard SELECT statement that specifies the selection criteria for
rows to include in the view. A SELECT in a view cannot include an ORDER BY clause. In
DSQL, it cannot include a UNION clause.
The optional WITH CHECK OPTION restricts inserts, updates, and deletes in a view that can
be updated.
To create a read-only view, a view’s creator must have SELECT privilege for the table or
tables underlying the view. To create a view for update requires ALL privilege for the table
or tables underlying the view. For more information about SQL privileges, see the security
chapter in the Data Definition Guide.
IMPORTANT Only a view’s creator initially has access to it. To assign read access to others, use GRANT.
For more information about GRANT, see the security chapter of the Data Definition
Guide.
Users who have INSERT and UPDATE privileges for this view can change rows in or add
new rows to the view’s underlying table, CITIES. They can even insert or update rows that
cannot be displayed by the HIGH_CITIES view. The following INSERT adds a record for
Santa Cruz, California, altitude 23 feet, to the CITIES table:
EXEC SQL
INSERT INTO HIGH_CITIES (CITY, COUNTRY_NAME, ALTITUDE)
VALUES (’Santa Cruz’, ’United States’, ’23’);
To restrict inserts and updates through a view to only those rows that can be selected by
the view, use the WITH CHECK OPTION in the view definition. For example, the following
statement defines the view, HIGH_CITIES, to use the WITH CHECK OPTION. Users with INSERT
and UPDATE privileges will be able to enter rows only for cities with altitudes greater than
or equal to a half mile.
EXEC SQL
CREATE VIEW HIGH_CITIES AS
SELECT CITY, COUNTRY_NAME, ALTITUDE FROM CITIES
WHERE ALTITUDE > 2640 WITH CHECK OPTION;
Creating an index
SQL provides CREATE INDEX for establishing user-defined database indexes. An index,
based on one or more columns in a table, is used to speed data retrieval for queries that
access those columns. The syntax for CREATE INDEX is:
96 INTERBASE 6
CREATING METADATA
EXEC SQL
CREATE [UNIQUE] [ASC[ENDING] | DESC[ENDING]] INDEX <index> ON
table (col [, col ...]);
For example, the following statement defines an index, NAMEX, for the LAST_NAME and
FIRST_NAME columns in the EMPLOYEE table:
EXEC SQL
CREATE INDEX NAMEX ON EMPLOYEE (LAST_NAME, FIRST_NAME);
Note InterBase automatically generates system-level indexes when tables are defined
using UNIQUE and PRIMARY KEY constraints. For more information about constraints, see
the Data Definition Guide.
See the Language Reference for more information about CREATE INDEX syntax.
IMPORTANT After a unique index is defined, users cannot insert or update values in indexed columns
if those values already exist there. For unique indexes defined on multiple columns, like
PRODTYPEX in the previous example, the same value can be entered within individual
columns, but the combination of values entered in all columns defined for the index
must be unique.
Note To retrieve indexed data in descending order, use ORDER BY in the SELECT statement
to specify retrieval order.
Creating generators
A generator is a monotonically increasing or decreasing numeric value that is inserted in
a field either directly by an SQL statement in an application or through a trigger.
Generators are often used to produce unique values to insert into a column used as a
primary key.
To create a generator for use in an application, use the following CREATE GENERATOR
syntax:
EXEC SQL
CREATE GENERATOR name;
Once a generator is created, the starting value for a generated number can be specified
with SET GENERATOR. To insert a generated number in a field, use the InterBase library
GEN_ID() function in an assignment statement. For more information about GEN_ID(),
CREATE GENERATOR, and SET GENERATOR, see the Data Definition Guide.
Dropping metadata
SQL supports several statements for deleting existing metadata:
g DROP TABLE, to delete a table from a database
g DROP VIEW, to delete a view definition from a database
g DROP INDEX, to delete a database index
g ALTER TABLE, to delete columns from a table
For more information about deleting columns with ALTER TABLE, see “Altering a table”
on page 101.
98 INTERBASE 6
DROPPING METADATA
Dropping an index
To delete an index, use DROP INDEX. An index can only be dropped by its creator, the
SYSDBA, or a user with root privileges. If an index is in use when the drop is attempted,
the drop is postponed until the index is no longer in use. The syntax of DROP INDEX is:
EXEC SQL
DROP INDEX name;
name is the name of the index to delete. For example, the following statement drops the
index, NEEDX:
EXEC SQL
DROP INDEX NEEDX;
EXEC SQL
COMMIT;
Deletion fails if the index is on a UNIQUE, PRIMARY KEY, or FOREIGN KEY integrity
constraint. To drop an index on a UNIQUE, PRIMARY KEY, or FOREIGN KEY integrity
constraint, first drop the constraints, the constrained columns, or the table.
For more information about DROP INDEX and dropping integrity constraints, see the Data
Definition Guide.
Dropping a view
To delete a view, use DROP VIEW. A view can only be dropped by its owner, the SYSDBA,
or a user with root privileges. If a view is in use when a drop is attempted, the drop is
postponed until the view is no longer in use. The syntax of DROP VIEW is:
EXEC SQL
DROP VIEW name;
Deleting a view fails if a view is used in another view, a trigger, or a computed column.
To delete a view that meets any of these conditions:
1. Delete the other view, trigger, or computed column.
2. Delete the view.
For more information about DROP VIEW, see the Data Definition Guide.
Dropping a table
Use DROP TABLE to remove a table from a database. A table can only be dropped by its
owner, the SYSDBA, or a user with root privileges. If a table is in use when a drop is
attempted, the drop is postponed until the table is no longer in use. The syntax of DROP
TABLE is:
EXEC SQL
DROP TABLE name;
name is the name of the table to drop. For example, the following statement drops the
EMPLOYEE table:
EXEC SQL
DROP TABLE EMPLOYEE;
EXEC SQL
COMMIT;
Deleting a table fails if a table is used in a view, a trigger, or a computed column. A table
cannot be deleted if a UNIQUE or PRIMARY KEY integrity constraint is defined for it, and
the constraint is also referenced by a FOREIGN KEY in another table. To drop the table, first
drop the FOREIGN KEY constraints in the other table, then drop the table.
Note Columns within a table can be dropped without dropping the rest of the table. For
more information, see “Dropping an existing column” on page 102.
For more information about DROP TABLE, see the Data Definition Guide.
Altering metadata
Most changes to data definitions are made at the table level, and involve adding new
columns to a table, or dropping obsolete columns from it. SQL provides ALTER TABLE to
add new columns to a table and to drop existing columns. A single ALTER TABLE can carry
out a single operation, or both operations.
Making changes to views and indexes always requires two separate statements:
1. Drop the existing definition.
2. Create a new definition.
If current metadata cannot be dropped, replacement definitions cannot be added.
Dropping metadata can fail for the following reasons:
100 INTERBASE 6
ALTERING METADATA
Altering a table
ALTER TABLE enables the following changes to an existing table:
g Adding new column definitions
g Adding new table constraints
g Dropping existing column definitions
g Dropping existing table constraints
g Changing column definitions by dropping existing definitions, and adding new ones
g Changing existing table constraints by dropping existing definitions, and adding new
ones
g Modifying column names and datatypes
The simple syntax of ALTER TABLE is as follows:
EXEC SQL
ALTER TABLE name {ADD colname <datatype> [NOT NULL]
| ALTER [COLUMN] simple_column_name alter_rel_field
| DROP colname | ADD CONSTRAINT constraintname tableconstraint
| DROP CONSTRAINT constraintname};
Note For information about adding, dropping, and modifying constraints at the table
level, see the Data Definition Guide.
For the complete syntax of ALTER TABLE, see the Language Reference.
For example, the following statement adds a column, EMP_NO, to the EMPLOYEE table:
EXEC SQL
ALTER TABLE EMPLOYEE ADD EMP_NO EMPNO NOT NULL;
EXEC SQL
COMMIT;
This example makes use of a domain, EMPNO, to define a column. For more information
about domains, see the Data Definition Guide.
Multiple columns can be added to a table at the same time. Separate column definitions
with commas. For example, the following statement adds two columns, EMP_NO, and
FULL_NAME, to the EMPLOYEE table. FULL_NAME is a computed column, a column that
derives it values from calculations based on other columns:
EXEC SQL
ALTER TABLE EMPLOYEE
ADD EMP_NO EMPNO NOT NULL,
ADD FULL_NAME COMPUTED BY (LAST_NAME || ’, ’ || FIRST_NAME);
EXEC SQL
COMMIT;
This example creates a column using a value computed from two other columns already
defined for the EMPLOYEE table. For more information about creating computed columns,
see the Data Definition Guide.
New columns added to a table can be defined with integrity constraints. For more
information about adding columns with integrity constraints to a table, see the Data
Definition Guide.
For example, the following statement drops the EMP_NO column from the EMPLOYEE table:
EXEC SQL
ALTER TABLE EMPLOYEE DROP EMP_NO;
EXEC SQL
COMMIT;
Multiple columns can be dropped with a single ALTER TABLE. The following statement
drops the EMP_NO and FULL_NAME columns from the EMPLOYEE table:
102 INTERBASE 6
ALTERING METADATA
EXEC SQL
ALTER TABLE EMPLOYEE
DROP EMP_NO,
DROP FULL_NAME;
EXEC SQL
COMMIT;
Deleting a column fails if the column is part of a UNIQUE, PRIMARY KEY, or FOREIGN KEY
constraint. To drop the column, first drop the constraint, then the column.
Deleting a column also fails if the column is used by a CHECK constraint for another
column. To drop the column, first drop the CHECK constraint, then drop the column.
For more information about integrity constraints, see the Data Definition Guide.
4 Modifying a column
An existing column definition can be modified using ALTER TABLE, but if data already
stored in that column is not preserved before making changes, it will be lost.
Preserving data entered in a column and modifying the definition for a column, is a
five-step process:
1. Adding a new, temporary column to the table that mirrors the current
metadata of the column to be changed.
2. Copying the data from the column to be changed to the newly created
temporary column.
3. Modifying the column.
4. Copying data from the temporary column to the redefined column.
5. Dropping the temporary column.
For example, suppose the EMPLOYEE table contains a column, OFFICE_NO, defined to hold
a datatype of CHAR(3), and suppose that the size of the column needs to be increased by
one. The following numbered sequence describes each step and provides sample code:
1. First, create a temporary column to hold the data in OFFICE_NO during the
modification process:
EXEC SQL
ALTER TABLE EMPLOYEE ADD TEMP_NO CHAR(3);
EXEC SQL
COMMIT;
2. Move existing data from OFFICE_NO to TEMP_NO to preserve it:
EXEC SQL
UPDATE EMPLOYEE
You could also change the name of the EMP_NO column to EMP_NUM as in the following
example:
ALTER TABLE EMPLOYEE ALTER EMP_NO TO EMP_NUM;
IMPORTANT Any changes to the field definitions may require the indexes to be rebuilt.
For the complete syntax of ALTER TABLE, see the Language Reference.
104 INTERBASE 6
ALTERING METADATA
Altering a view
To change the information provided by a view, follow these steps:
1. Drop the current view definition.
2. Create a new view definition and give it the same name as the dropped view.
For example, the following view is defined to select employee salary information:
EXEC SQL
CREATE VIEW EMPLOYEE_SALARY AS
SELECT EMP_NO, LAST_NAME, CURRENCY, SALARY
FROM EMPLOYEE, COUNTRY
WHERE EMPLOYEE.COUNTRY_CODE = COUNTRY.CODE;
Suppose the full name of each employee should be displayed instead of the last name.
First, drop the current view definition:
EXEC SQL
DROP EMPLOYEE_SALARY;
EXEC SQL
COMMIT;
Then create a new view definition that displays each employee’s full name:
EXEC SQL
CREATE VIEW EMPLOYEE_SALARY AS
SELECT EMP_NO, FULL_NAME, CURRENCY, SALARY
FROM EMPLOYEE, COUNTRY
WHERE EMPLOYEE.COUNTRY_CODE = COUNTRY.CODE;
EXEC SQL
COMMIT;
Altering an index
To change the definition of an index, follow these steps:
1. Use ALTER INDEX to make the current index inactive.
2. Drop the current index.
3. Create a new index and give it the same name as the dropped index.
An index is usually modified to change the combination of columns that are indexed, to
prevent or allow insertion of duplicate entries, or to specify index sort order. For example,
given the following definition of the NAMEX index:
EXEC SQL
CREATE INDEX NAMEX ON EMPLOYEE (LAST_NAME, FIRST_NAME);
Suppose there is an additional need to prevent duplicate entries with the UNIQUE
keyword. First, make the current index inactive, then drop it:
EXEC SQL
ALTER INDEX NAMEX INACTIVE;
EXEC SQL
DROP INDEX NAMEX;
EXEC SQL
COMMIT;
Then create a new index, NAMEX, based on the previous definition, that also includes the
UNIQUE keyword:
EXEC SQL
CREATE UNIQUE INDEX NAMEX ON EMPLOYEE (LAST_NAME, FIRST_NAME);
EXEC SQL
COMMIT
ALTER INDEX can be used directly to change an index’s sort order, or to add the ability to
handle unique or duplicate entries. For example, the following statement changes the
NAMEX index to permit duplicate entries:
EXEC SQL
ALTER INDEX NAMEX DUPLICATE;
IMPORTANT Be careful when altering an index directly. For example, changing an index from
supporting duplicate entries to one that requires unique entries without disabling the
index and recreating it can reduce index performance.
For more information about dropping an index, see “Dropping an index” on page 99.
For more information about creating an index, see “Creating an index” on page 96.
106 INTERBASE 6
CHAPTER
To learn how to use the SELECT statement to retrieve data, see “Understanding data
retrieval with SELECT” on page 126. For information about retrieving a single row with
SELECT, see “Selecting a single row” on page 143. For information about retrieving
multiple rows, see “Selecting multiple rows” on page 144.
For information about using INSERT to write new data to a table, see “Inserting data” on
page 164. To modify data with UPDATE, see “Updating data” on page 170. To remove
data from a table with DELETE, see “Deleting data” on page 176.
Supported datatypes
To query or write to a table, it is necessary to know the structure of the table, what
columns it contains, and what datatypes are defined for those columns. InterBase
supports ten fundamental datatypes, described in the following table:
DECIMAL (precision, scale) Variable • precision = 1 to 18; specifies at least • Number with a decimal point scale
(16, 32, or precision digits of precision to store digits from the right
64 bits) • scale = 1 to 18; specifies number of • Example: DECIMAL(10, 3) holds
decimal places for storage numbers accurately in the following
• Must be less than or equal to precision format: ppppppp.sss
DOUBLE PRECISION 64 bitsa 2.225 x 10–308 to 1.797 x 10308 IEEE double precision: 15 digits
FLOAT 32 bits 1.175 x 10–38 to 3.402 x 1038 IEEE single precision: 7 digits
INTEGER 32 bits –2,147,483,648 to 2,147,483,647 Signed long (longword)
TABLE 6.1 Datatypes supported by InterBase
108 INTERBASE 6
SUPPORTED DATATYPES
TIMESTAMP 64 bits 1 Jan 100 a.d. to 29 Feb 32768 a.d. ISC_TIMESTAMP; contains both date and
time information
VARCHAR (n) n characters • 1 to 32,765 bytes • Variable length CHAR or text string
• Character set character size determines type
the maximum number of characters • Alternate keywords: CHAR VARYING,
that can fit in 32K CHARACTER VARYING
a. Actual size of DOUBLE is platform-dependent. Most platforms support the 64-bit size.
The BLOB datatype can store large data objects of indeterminate and variable size, such
as bitmapped graphics images, vector drawings, sound files, chapter or book-length
documents, or any other kind of multimedia information. Because a Blob can hold
different kinds of information, it requires special processing for reading and writing. For
more information about Blob handling, see Chapter 8, “Working with Blob Data.”
The DATE, TIME, and TIMESTAMP datatypes may require conversion to and from InterBase when
entered or manipulated in a host-language program. For more information about
retrieving and writing dates, see Chapter 7, “Working with Dates.”
InterBase also supports arrays of most datatypes. An array is a matrix of individual items,
all of any single InterBase datatype, except Blob, that can be handled either as a single
entity, or manipulated item by item. To learn more about the flexible data access provided
by arrays, see Chapter 9, “Using Arrays.”
For a complete discussion of InterBase datatypes, see the Data Definition Guide.
Element Description
Column names Columns from specified tables, against which to search or compare values,
or from which to calculate values.
Host-language variables Program variables containing changeable values. Host-language
variables must be preceded by a colon (:).
Constants Hard-coded numbers or quoted strings, like 507 or “Tokyo”.
Concatenation operator ||, used to combine character strings.
Arithmetic operators +, –, *, and /, used to calculate and evaluate values.
Logical operators Keywords, NOT, AND, and OR, used within simple search conditions, or to
combine simple search conditions to make complex searches. A logical
operation evaluates to true or false. Usually used only in search conditions.
TABLE 6.2 Elements of SQL expressions
110 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
Element Description
Comparison operators <, >, <=, >=, =, and <>, used to compare a value on the left side of the
operator to another on the right. A comparative operation evaluates to
true or false.
Other, more specialized comparison operators include ALL, ANY, BETWEEN,
CONTAINING, EXISTS, IN, IS, LIKE, NULL, SINGULAR, SOME, and STARTING WITH.
These operators can evaluate to True, False, or Unknown. They are usually
used only in search conditions.
COLLATE clause Comparisons of CHAR and VARCHAR values can sometimes take advantage
of a COLLATE clause to force the way text values are compared.
Stored procedures Reusable SQL statement blocks that can receive and return parameters,
and that are stored as part of a database’s metadata.
Subqueries SELECT statements, typically nested in WHERE clauses, that return values to
be compared with the result set of the main SELECT statement.
Parentheses Used to group expressions into hierarchies; operations inside parentheses
are performed before operations outside them. When parentheses are
nested, the contents of the innermost set is evaluated first and evaluation
proceeds outward.
Date literals String values that can be entered in quotes and be interpreted as date
values in SELECT, INSERT, and UPDATE operations. Possible strings are ‘ TODAY’,
‘NOW’, ‘YESTERDAY’, and ‘TOMORROW’.
The USER pseudocolumn References the name of the user who is currently logged in. For example,
USER can be used as a default in a column definition or to enter the current
user’s name in an INSERT. When a user name is present in a table, it can be
referenced with USER in SELECT and DELETE statements.
TABLE 6.2 Elements of SQL expressions (continued)
As another example, search conditions in WHERE clauses often contain nested SELECT
statements, or subqueries. In the following query, the WHERE clause contains a subquery
that uses the aggregate function, AVG(), to retrieve a list of all departments with bigger
than average salaries:
EXEC SQL
DECLARE WELL_PAID CURSOR FOR
SELECT DEPT_NO
INTO :wellpaid
FROM DEPARTMENT
WHERE SALARY > (SELECT AVG(SALARY) FROM DEPARTMENT);
For more information about using subqueries to specify search conditions, see “Using
subqueries” on page 161. For more information about aggregate functions, see
“Retrieving aggregate column information” on page 129.
112 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
Arithmetic operators are evaluated from left to right, except when ambiguities arise. In
these cases, InterBase evaluates operations according to the precedence specified in the
table (for example, multiplications are performed before divisions, and divisions are
performed before subtractions).
Arithmetic operations are always calculated before comparison and logical operations. To
change or force the order of evaluation, group operations in parentheses. InterBase
calculates operations within parentheses first. If parentheses are nested, the equation in
the innermost set is the first evaluated, and the outermost set is evaluated last. For more
information about precedence and using parentheses for grouping, see “Determining
precedence of operators” on page 122.
The following example illustrates a WHERE clause search condition that uses an arithmetic
operator to combine the values from two columns, then uses a comparison operator to
determine if that value is greater than 10:
DECLARE RAINCITIES CURSOR FOR
SELECT CITYNAME, COUNTRYNAME
INTO :cityname, :countryname
FROM CITIES
WHERE JANUARY_RAIN + FEBRUARY_RAIN > 10;
When AND appears between search conditions, both search conditions must be true if a
row is to be retrieved. The following query returns any employee whose last name is
neither “Smith” nor “Jones”:
DECLARE NO_SMITH_OR_JONES CURSOR FOR
SELECT LAST_NAME
INTO :lname
FROM EMPLOYEE
WHERE NOT LNAME = ’Smith’ AND NOT LNAME = ’Jones’;
OR stipulates that one search condition or the other must be true. For example, the
following query returns any employee named “Smith” or “Jones”:
DECLARE ALL_SMITH_JONES CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
INTO :lname, :fname
FROM EMPLOYEE
WHERE LNAME = ’Smith’ OR LNAME = ’Jones’;
The order in which combined search conditions are evaluated is dictated by the
precedence of the operators that connect them. A NOT condition is evaluated before AND,
and AND is evaluated before OR. Parentheses can be used to change the order of
evaluation. For more information about precedence and using parentheses for grouping,
see “Determining precedence of operators” on page 122.
114 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
For more information about CAST(), see “Using CAST( ) for datatype conversions” on
page 125.
InterBase also supports comparison operators that compare a value on the left of the
operator to the results of a subquery to the right of the operator. The following table lists
these operators, and describes how they are used:
Operator Purpose
ALL Determines if a value is equal to all values returned by a subquery
ANY and SOME Determines if a value is equal to any values returned by a subquery
EXISTS Determines if a value exists in at least one value returned by a subquery
SINGULAR Determines if a value exists in exactly one value returned by a subquery
TABLE 6.4 InterBase comparison operators requiring subqueries
For more information about using subqueries, see “Using subqueries” on page 161.
4 Using BETWEEN
BETWEEN tests whether a value falls within a range of values. The complete syntax for the
BETWEEN operator is:
<value> [NOT] BETWEEN <value> AND <value>
For example, the following cursor declaration retrieves LAST_NAME and FIRST_NAME
columns for employees with salaries between $100,000 and $250,000, inclusive:
EXEC SQL
DECLARE LARGE_SALARIES CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE SALARY BETWEEN 100000 AND 250000;
Use NOT BETWEEN to test whether a value falls outside a range of values. For example, the
following cursor declaration retrieves the names of employees with salaries less than
$30,000 and greater than $150,000:
EXEC SQL
DECLARE EXTREME_SALARIES CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE SALARY NOT BETWEEN 30000 AND 150000;
4 Using CONTAINING
CONTAINING tests to see if an ASCII string value contains a quoted ASCII string supplied
by the program. String comparisons are case-insensitive; “String”, “STRING”, and “string”
are equivalent values for CONTAINING. Note that for Dialect 3 databases and clients, the
strings must be enclosed in single quotation marks. The complete syntax for CONTAINING
is:
<value> [NOT] CONTAINING ’<string>’
For example, the following cursor declaration retrieves the names of all employees whose
last names contain the three-letter combination, “las” (and “LAS” or “Las”):
EXEC SQL
DECLARE LAS_EMP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE LAST_NAME CONTAINING ’las’;
Use NOT CONTAINING to test for strings that exclude a specified value. For example, the
following cursor declaration retrieves the names of all employees whose last names do
not contain “las” (also “LAS” or “Las”):
EXEC SQL
DECLARE NOT_LAS_EMP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE LAST_NAME NOT CONTAINING ’las’;
Tip CONTAINING can be used to search a Blob segment by segment for an occurrence of a
quoted string.
4 Using IN
IN tests that a known value equals at least one value in a list of values. A list is a set of
values separated by commas and enclosed by parentheses. The values in the list must be
parenthesized and separated by commas. If the value being compared to a list of values
is NULL, IN returns Unknown.
The syntax for IN is:
<value> [NOT] IN (<value> [, <value> ...])
116 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
For example, the following cursor declaration retrieves the names of all employees in the
accounting, payroll, and human resources departments:
EXEC SQL
DECLARE ACCT_PAY_HR CURSOR FOR
SELECT DEPARTMENT, LAST_NAME, FIRST_NAME, EMP_NO
FROM EMPLOYEE EMP, DEPTARTMENT DEP
WHERE EMP.DEPT_NO = DEP.DEPT_NO AND
DEPARTMENT IN (’Accounting’, ’Payroll’, ’Human Resources’)
GROUP BY DEPARTMENT;
Use NOT IN to test that a value does not occur in a set of specified values. For example,
the following cursor declaration retrieves the names of all employees not in the
accounting, payroll, and human resources departments:
EXEC SQL
DECLARE NOT_ACCT_PAY_HR CURSOR FOR
SELECT DEPARTMENT, LAST_NAME, FIRST_NAME, EMP_NO
FROM EMPLOYEE EMP, DEPTARTMENT DEP
WHERE EMP.DEPT_NO = DEP.DEPT_NO AND
DEPARTMENT NOT IN (’Accounting’, ’Payroll’,
’Human Resources’)
GROUP BY DEPARTMENT;
IN can also be used to compare a value against the results of a subquery. For example,
the following cursor declaration retrieves all cities in Europe:
EXEC SQL
DECLARE NON_JFG_CITIES CURSOR FOR
SELECT C.COUNTRY, C.CITY, C.POPULATION
FROM CITIES C
WHERE C.COUNTRY NOT IN (SELECT O.COUNTRY FROM COUNTRIES O
WHERE O.CONTINENT <> ’Europe’)
GROUP BY C.COUNTRY;
For more information about subqueries, see “Using subqueries” on page 161.
4 Using LIKE
LIKE is a case-sensitive operator that tests a string value against a string containing
wildcards, symbols that substitute for a single, variable character, or a string of variable
characters. LIKE recognizes two wildcard symbols:
g % (percent) substitutes for a string of zero or more characters.
g _ (underscore) substitutes for a single character.
For example, this cursor retrieves information about any employee whose last names
contain the three letter combination “ton” (but not “Ton”):
EXEC SQL
DECLARE TON_EMP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, EMP_NO
FROM EMPLOYEE
WHERE LAST_NAME LIKE ’%ton%’;
Use NOT LIKE to retrieve rows that do not contain strings matching those described. For
example, the following cursor retrieves all table names in RDB$RELATIONS that do not have
underscores in their names:
EXEC SQL
DECLARE NOT_UNDER_TABLE CURSOR FOR
SELECT RDB$RELATION_NAME
FROM RDB$RELATIONS
WHERE RDB$RELATION_NAME NOT LIKE ’%@_%’ ESCAPE ’@’;
4 Using IS NULL
IS NULL tests for the absence of a value in a column. The complete syntax of the IS NULL
clause is:
<value> IS [NOT] NULL
118 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
For example, the following cursor retrieves the names of employees who do not have
phone extensions:
EXEC SQL
DECLARE MISSING_PHONE CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE PHONE_EXT IS NULL;
Use IS NOT NULL to test that a column contains a value. For example, the following cursor
retrieves the phone numbers of all employees that have phone extensions:
EXEC SQL
DECLARE PHONE_LIST CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, PHONE_EXT
FROM EMPLOYEE
WHERE PHONE_EXT IS NOT NULL
ORDER BY LAST_NAME, FIRST_NAME;
For example, the following cursor retrieves employee last names that start with “To”:
EXEC SQL
DECLARE TO_EMP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE LAST_NAME STARTING WITH ’To’;
Use NOT STARTING WITH to retrieve information for columns that do not begin with the
stipulated string. For example, the following cursor retrieves all employees except those
whose last names start with “To”:
EXEC SQL
DECLARE NOT_TO_EMP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME
FROM EMPLOYEE
WHERE LAST_NAME NOT STARTING WITH ’To’;
For more information about collation order and byte-matching rules, see the Data
Definition Guide.
4 Using ALL
ALL tests that a value is true when compared to every value in a list returned by a
subquery. The complete syntax for ALL is:
<value> <comparison_operator> ALL (<subquery>)
For example, the following cursor retrieves information about employees whose salaries
are larger than that of the vice president of channel marketing:
EXEC SQL
DECLARE MORE_THAN_VP CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, SALARY
FROM EMPLOYEE
WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE
WHERE DEPT_NO = 7734);
ALL returns Unknown if the subquery returns a NULL value. It can also return Unknown
if the value to be compared is NULL and the subquery returns any non-NULL data. If the
value is NULL and the subquery returns an empty set, ALL evaluates to True.
For more information about subqueries, see “Using subqueries” on page 161.
For example, the following cursor retrieves information about salaries that are larger than
at least one salary in the channel marketing department:
EXEC SQL
DECLARE MORE_CHANNEL CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, SALARY
FROM EMPLOYEE
WHERE SALARY > ANY (SELECT SALARY FROM EMPLOYEE
WHERE DEPT_NO = 7734);
ANY and SOME return Unknown if the subquery returns a NULL value. They can also return
Unknown if the value to be compared is NULL and the subquery returns any non-NULL
data. If the value is NULL and the subquery returns an empty set, ANY and SOME evaluate
to False.
For more information about subqueries, see “Using subqueries” on page 161.
120 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
4 Using EXISTS
EXISTS tests that for a given value there is at least one qualifying row meeting the search
condition specified in a subquery. The SELECT clause in the subquery must use the *
(asterisk) to select all columns. The complete syntax for EXISTS is:
[NOT] EXISTS (SELECT * FROM <tablelist> WHERE <search_condition>)
Use NOT EXISTS to retrieve rows that do not meet the qualifying condition specified in the
subquery. The following cursor retrieves all countries without rivers:
EXEC SQL
DECLARE NON_RIVER_COUNTRIES COUNTRIES FOR
SELECT COUNTRY
FROM COUNTRIES C
WHERE NOT EXISTS (SELECT * FROM RIVERS R
WHERE R.COUNTRY = C.COUNTRY);
EXISTS always returns either True or False, even when handling NULL values.
For more information about subqueries, see “Using subqueries” on page 161.
4 Using SINGULAR
SINGULAR tests that for a given value there is exactly one qualifying row meeting the
search condition specified in a subquery. The SELECT clause in the subquery must use the
* (asterisk) to select all columns. The complete syntax for SINGULAR is:
[NOT] SINGULAR (SELECT * FROM <tablelist> WHERE <search_condition>)
Use NOT SINGULAR to retrieve rows that do not meet the qualifying condition specified in
the subquery. For example, the following cursor retrieves all countries with more than
one capital:
EXEC SQL
DECLARE MULTI_CAPITAL CURSOR FOR
SELECT COUNTRY
FROM COUNTRIES COU
WHERE NOT SINGULAR (SELECT * FROM CITIES CIT
WHERE CIT.CITY = COU.CAPITAL);
For more information about subqueries, see “Using subqueries” on page 161.
122 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
InterBase also follows rules for determining the order in which comparison operators are
evaluated when conflicts arise during normal left to right evaluation. The next table
describes the evaluation order for comparison operators, from highest to lowest:
ALL, ANY, BETWEEN, CONTAINING, EXISTS, IN, LIKE, NULL, SINGULAR, SOME, and STARTING
WITH are evaluated after all listed comparison operators when they conflict with other
comparison operators during normal left to right evaluation. When they conflict with one
another they are evaluated strictly from left to right.
When logical operators conflict during normal left to right processing, they, too, are
evaluated according to a hierarchy, detailed in the following table:
Tip Always use parentheses to group operations in complex expressions, even when default
order of evaluation is desired. Explicitly grouped expressions are easier to understand
and debug.
124 INTERBASE 6
UNDERSTANDING SQL EXPRESSIONS
For example, in the following WHERE clause, CAST() is used to translate a CHAR datatype,
INTERVIEW_DATE, to a DATE datatype to compare against a DATE datatype, HIRE_DATE:
WHERE HIRE_DATE = CAST(INTERVIEW_DATE AS DATE);
CAST() can be used to compare columns with different datatypes in the same table, or
across tables. You can convert one datatype to another as shown in the following table:
An error results if a given datatype cannot be converted into the datatype specified in
CAST().
. . .
printf("Enter new department name: ");
response[0] = ’\0’;
gets(response);
if (response)
EXEC SQL
INSERT INTO DEPARTMENT(DEPT_NO, DEPARTMENT)
VALUES(GEN_ID(GDEPT_NO, 1), UPPER(:response));
. . .
The next statement illustrates how UPPER() can be used in a SELECT statement to affect
both the appearance of values retrieved, and to affect its search condition:
EXEC SQL
SELECT DEPT_NO, UPPER(DEPARTMENT)
FROM DEPARTMENT
WHERE UPPER(DEPARTMENT) STARTING WITH ’A’;
126 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
Tip Host variables must be declared in a program before they can be used in SQL
statements. For more information about declaring host variables, see Chapter 2,
“Application Requirements.”
The following table lists all SELECT statement clauses, in the order that they are used, and
prescribes their use in singleton and multi-row selects:
Singleton Multi-row
Clause Purpose SELECT SELECT
SELECT Lists columns to retrieve. Required Required
INTO Lists host variables for storing retrieved columns. Required Not allowed
FROM Identifies the tables to search for values. Required Required
WHERE Specifies the search conditions used to restrict retrieved Optional Optional
rows to a subset of all available rows. A WHERE clause can
contain its own SELECT statement, referred to as a subquery.
GROUP BY Groups related rows based on common column values. Optional Optional
Used in conjunction with HAVING.
HAVING Restricts rows generated by GROUP BY to a subset of those Optional Optional
rows.
UNION Combines the results of two or more SELECT statements to Optional Optional
produce a single, dynamic table without duplicate rows.
PLAN Specifies the query plan that should be used by the query Optional Optional
optimizer instead of one it would normally choose.
ORDER BY Specifies the sort order of rows returned by a SELECT, either Optional Optional
ascending (ASC), the default, or descending (DESC).
FOR UPDATE Specifies columns listed after the SELECT clause of a DECLARE Not allowed Optional
CURSOR statement that can be updated using a WHERE
CURRENT OF clause.
Using each of these clauses with SELECT is described in the following sections, after which
using SELECT directly to return a single row, and using SELECT within a DECLARE CURSOR
statement to return multiple rows are described in detail. For a complete overview of
SELECT syntax, see the Language Reference.
IMPORTANT You must provide one host variable for each column returned by a query.
To eliminate duplicate columns in such a query, use the DISTINCT keyword with SELECT.
For example, the following SELECT yields only a single instance of “Smith”:
128 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
EXEC SQL
DECLARE SMITH CURSOR FOR
SELECT DISTINCT LAST_NAME
FROM EMPLOYEE
WHERE LAST_NAME = ’Smith’;
Function Purpose
AVG() Calculates the average numeric value for a set of values.
MIN() Retrieves the minimum value in a set of values.
MAX() Retrieves the maximum value in a set of values.
SUM() Calculates the total of numeric values in a set of values.
COUNT() Calculates the number of rows that satisfy the query’s search condition
(specified in the WHERE clause).
TABLE 6.11 Aggregate functions in SQL
For example, the following query returns the average salary for all employees in the
EMPLOYEE table:
EXEC SQL
SELECT AVG(SALARY)
INTO :avg_sal
FROM EMPLOYEE;
The following SELECT returns the number of qualifying rows it encounters in the
EMPLOYEE table, both the maximum and minimum employee number of employees in the
table, and the total salary of all employees in the table:
EXEC SQL
SELECT COUNT(*), MAX(EMP_NO), MIN(EMP_NO), SUM(SALARY)
INTO :counter, :maxno, :minno, :total_salary
FROM EMPLOYEE;
If a field value involved in an aggregate calculation is NULL or unknown, the entire row
is automatically excluded from the calculation. Automatic exclusion prevents averages
from being skewed by meaningless data.
Note Aggregate functions can also be used to calculate values for groups of rows. The
resulting value is called a group aggregate. For more information about using group
aggregates, see “Grouping rows with GROUP BY” on page 139.
130 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
For a complete discussion of transaction handling and naming, see Chapter 4, “Working
with Transactions.”
Note In a multi-row select, the INTO clause is part of the FETCH statement, not the SELECT
statement. For more information about the INTO clause in FETCH, see “Fetching rows
with a cursor” on page 147.
There must be at least one table, view, or select procedure name following the FROM
keyword. When retrieving data from multiple sources, each source must be listed,
assigned an alias, and separated from the next with a comma. For more information
about select procedures, see Chapter 10, “Working with Stored Procedures.”
Use the same INTO clause syntax to specify a view or select procedure as the source for
data retrieval instead of a table. For example, the following SELECT specifies a select
procedure, MVIEW, from which to retrieve data. MVIEW returns information for all
managers whose last names begin with the letter “M,” and the WHERE clause narrows the
rows returned to a single row where the DEPT_NO column is 430:
EXEC SQL
SELECT DEPT_NO, LAST_NAME, FIRST_NAME, SALARY
INTO :lname, :fname, :salary
FROM MVIEW
WHERE DEPT_NO = 430;
For more information about select procedures, see Chapter 10, “Working with
Stored Procedures.”
132 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
In the second case, column names that occur in two or more tables must be distinguished
from one another by preceding each column name with its table name and a period in
the SELECT clause. For example, if an EMP_NO column exists in both the DEPARTMENT and
EMPLOYEE then the previous query must be recast as follows:
EXEC SQL
SELECT DEPARTMENT, DEPT_NO, LAST_NAME, FIRST_NAME,
EMLOYEE.EMP_NO
INTO :dept_name, :dept_no, :lname, :fname, :empno
FROM DEPARTMENT, EMPLOYEE
WHERE DEPT_NO = ’Publications’ AND
DEPARTMENT.EMP_NO = EMPLOYEE.EMP_NO;
For more information about the SELECT clause, see “Listing columns to retrieve with
SELECT” on page 128.
IMPORTANT For queries involving joins, column names can be qualified by correlation names, brief
alternate names, or aliases, that are assigned to each table in a FROM clause and
substituted for them in other SELECT statement clauses when qualifying column names.
Even when joins are not involved, assigning and using correlation names can reduce the
length of complex queries.
Like an actual table name, a correlation name is used to qualify column names wherever
they appear in a SELECT statement. For example, the following query employs the
correlation names, DEPT, and EMP, previously described:
EXEC SQL
SELECT DEPARTMENT, DEPT_NO, LAST_NAME, FIRST_NAME,
EMLOYEE.EMP_NO
INTO :dept_name, :dept_no, :lname, :fname, :empno
FROM DEPARTMENT DEPT, EMPLOYEE EMP
WHERE DEPT_NO = ’Publications’ AND DEPT.EMP_NO = EMP.EMP_NO;
For more information about the SELECT clause, see “Listing columns to retrieve with
SELECT” on page 128.
For example, the following simple WHERE clause tests a row to see if the
DEPARTMENT column is “Publications”:
134 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
This search condition has three elements: a column name, a comparison operator (the
equal sign), and a constant. Most search conditions are more complex than this. They
involve additional elements and combinations of simple search conditions. The following
table describes expression elements that can be used in search conditions:
Element Description
Column names Columns from tables listed in the FROM clause, against which to search or
compare values.
Host-language variables Program variables containing changeable values. When used in a SELECT,
host-language variables must be preceded by a colon (:).
Constants Hard-coded numbers or quoted strings, like 507 or “Tokyo”.
Concatenation operators ||, used to combine character strings.
Arithmetic operators +, –, *, and /, used to calculate and evaluate search condition values.
Logical operators Keywords, NOT, AND, and OR, used within simple search conditions, or to
combine simple search conditions to make complex searches. A logical
operation evaluates to true or false.
Comparison operators <, >, <=, >=, =, and <>, used to compare a value on the left side of the
operator to another on the right. A comparative operation evaluates to
True or False.
Other, more specialized comparison operators include ALL, ANY, BETWEEN,
CONTAINING, EXISTS, IN, IS, LIKE, NULL, SINGULAR, SOME, and STARTING WITH.
These operators can evaluate to True, False, or Unknown.
COLLATE clause Comparisons of CHAR and VARCHAR values can sometimes take advantage
of a COLLATE clause to force the way text values are compared.
Stored procedures Reusable SQL statement blocks that can receive and return parameters,
and that are stored as part of a database’s metadata. For more information
about stored procedures in queries, see Chapter 10, “Working with
Stored Procedures.”
Subqueries A SELECT statement nested within the WHERE clause to return or calculate
values against which rows searched by the main SELECT statement are
compared. For more information about subqueries, see “Using
subqueries” on page 161.
Parentheses Group related parts of search conditions which should be processed
separately to produce a single value which is then used to evaluate the
search condition. Parenthetical expressions can be nested.
TABLE 6.12 Elements of WHERE clause SEARCH conditions
136 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
For a general discussion of building search conditions from SQL expressions, see
“Understanding SQL expressions” on page 110. For more information about using
subqueries to specify search conditions, see “Using subqueries” on page 161. For more
information about aggregate functions, see “Retrieving aggregate column
information” on page 129.
For more information about collation order and a list of collations available to InterBase,
see the Data Definition Guide.
For example, the following cursor declaration orders output based on the LAST_NAME
column. Because DESC is specified in the ORDER BY clause, employees are retrieved from
Z to A:
EXEC SQL
DECLARE PHONE_LIST CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, PHONE_EXT
FROM EMPLOYEE
WHERE PHONE_EXT IS NOT NULL
ORDER BY LAST_NAME DESC, FIRST_NAME;
IMPORTANT In multi-column sorts, after a sort order is specified, it applies to all subsequent columns
until another sort order is specified, as in the previous example. This attribute is
sometimes called sticky sort order. For example, the following cursor declaration orders
retrieval by LAST_NAME in descending order, then refines it alphabetically within
LAST_NAME groups by FIRST_NAME in ascending order:
EXEC SQL
DECLARE PHONE_LIST CURSOR FOR
SELECT LAST_NAME, FIRST_NAME, PHONE_EXT
FROM EMPLOYEE
WHERE PHONE_EXT IS NOT NULL
ORDER BY LAST_NAME DESC, FIRST_NAME ASC;
138 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
For more information about collation order and a list of available collations in InterBase,
see the Data Definition Guide.
For example, consider two cursor declarations. The first declaration returns the names of
all employees each department, and arranges retrieval in ascending alphabetic order by
department and employee name.
EXEC SQL
DECLARE DEPT_EMP CURSOR FOR
SELECT DEPARTMENT, LAST_NAME, FIRST_NAME
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DEPT_NO = E.DEPT_NO
ORDER BY DEPARTMENT, LAST_NAME, FIRST_NAME;
In contrast, the next cursor illustrates the use of aggregate functions with GROUP BY to
return results known as group aggregates. It returns the average salary of all employees
in each department. The GROUP BY clause assures that average salaries are calculated and
retrieved based on department names, while the ORDER BY clause arranges retrieved rows
alphabetically by department name.
EXEC SQL
DECLARE AVG_DEPT_SAL CURSOR FOR
SELECT DEPARTMENT, AVG(SALARY)
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DEPT_NO = E.DEPT_NO
GROUP BY DEPARTMENT
ORDER BY DEPARTMENT;
For more information about collation order and a list of collation orders available in
InterBase, see the Data Definition Guide.
4 Limitations of GROUP BY
When using GROUP BY, be aware of the following limitations:
g Each column name that appears in a GROUP BY clause must also be specified in the SELECT
clause.
g GROUP BY cannot specify a column whose values are derived from a mathematical,
aggregate, or user-defined function.
g GROUP BY cannot be used in SELECT statements that:
· Contain an INTO clause (singleton selects).
· Use a subquery with a FROM clause which references a view whose definition contains
a GROUP BY or HAVING clause.
g For each SELECT clause in a query, including subqueries, there can only be one GROUP BY
clause.
140 INTERBASE 6
UNDERSTANDING DATA RETRIEVAL WITH SELECT
HAVING uses search conditions that are like the search conditions that can appear in the
WHERE clause, but with the following restrictions:
g Each search condition usually corresponds to an aggregate function used in the SELECT
clause.
g The FROM clause of a subquery appearing in a HAVING clause cannot name any table or
view specified in the main query’s FROM clause.
g A correlated subquery cannot be used in a HAVING clause.
For example, the following cursor declaration returns the average salary for all employees
in each department. The GROUP BY clause assures that average salaries are calculated and
retrieved based on department names. The HAVING clause restricts retrieval to those
groups where the average salary is greater than 60,000, while the ORDER BY clause
arranges retrieved rows alphabetically by department name.
EXEC SQL
DECLARE SIXTY_THOU CURSOR FOR
SELECT DEPARTMENT, AVG(SALARY)
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DEPT_NO = E.DEPT_NO
GROUP BY DEPARTMENT
HAVING AVG(SALARY) > 60000
ORDER BY DEPARTMENT;
Note HAVING can also be used without GROUP BY. In this case, all rows retrieved by a
SELECT are treated as a single group, and each column named in the SELECT clause is
normally operated on by an aggregate function.
For more information about search conditions, see “Restricting row retrieval with
WHERE” on page 134. For more information about subqueries, see “Using subqueries”
on page 161.
For example, three tables, CITIES, COUNTRIES, and NATIONAL_PARKS, each contain the
names of cities. Assuming triggers have not been created that ensure that a city entered
in one table is also entered in the others to which it also applies, UNION can be used to
retrieve the names of all cities that appear in any of these tables.
EXEC SQL
DECLARE ALLCITIES CURSOR FOR
SELECT CIT.CITY FROM CITIES CIT
UNION SELECT COU.CAPITAL FROM COUNTRIES COU
UNION SELECT N.PARKCITY FROM NATIONAL_PARKS N;
Tip If two or more tables share entirely identical structures—similarly named columns,
identical datatypes, and similar data values in each column—UNION can return all rows
for each table by substituting an asterisk (*) for specific column names in the SELECT
clauses of the UNION.
142 INTERBASE 6
SELECTING A SINGLE ROW
The PLAN syntax enables specifying a single table, or a join of two or more tables in a
single pass. Plan expressions can be nested in parentheses to specify any combination of
joins.
During retrieval, information from different tables is joined to speed retrieval. If indexes
are defined for the information to be joined, then these indexes are used to perform a
join. The optional JOIN keyword can be used to document this type of operation. When
no indexes exist for the information to join, retrieval speed can be improved by specifying
SORT MERGE instead of JOIN.
A plan_item is the name of a table to search for data. If a table is used more than once
in a query, aliases must be used to distinguish them in the PLAN clause. Part of the
plan_item specification indicates the way that rows should be accessed. The following
choices are possible:
g NATURAL, the default order, specifies that rows are accessed sequentially in no defined
order. For unindexed items, this is the only option.
g INDEX specifies that one or more indexes should be used to access items. All indexes to
be used must be specified. If any Boolean or join terms remain after all indexes are used,
they will be evaluated without benefit of an index. If any indexes are specified that cannot
be used, an error is returned.
g ORDER specifies that items are to be sorted based on a specified index.
The mandatory INTO clause specifies the host variables where retrieved data is copied for
use in the program. Each host variable’s name must be preceded by a colon (:). For each
column retrieved, there must be one host variable of a corresponding datatype. Columns
are retrieved in the order they are listed in the SELECT clause, and are copied into host
variables in the order the variables are listed in the INTO clause.
The WHERE clause must specify a search condition that guarantees that only one row is
retrieved. If the WHERE clause does not reduce the number of rows returned to a single
row, the SELECT fails.
IMPORTANT To select data from a table, a user must have SELECT privilege for a table, or a stored
procedure invoked by the user’s application must have SELECT privileges for the table.
For example, the following SELECT retrieves information from the
DEPARTMENT table for the department, Publications:
EXEC SQL
SELECT DEPARTMENT, DEPT_NO, HEAD_DEPT, BUDGET, LOCATION, PHONE_NO
INTO :deptname, :dept_no, :manager, :budget, :location, :phone
FROM DEPARTMENT
WHERE DEPARTMENT = ’Publications’;
When SQL retrieves the specified row, it copies the value in DEPARTMENT to the host
variable, deptname, copies the value in DEPT_NO to :dept_no, copies the value in
HEAD_DEPT to :manager, and so on.
IMPORTANT In dynamic SQL (DSQL), the process for creating a query and retrieving data is
somewhat different. For more information about multi-row selection in DSQL, see
“Selecting multiple rows in DSQL” on page 152.
To retrieve multiple rows into a results table, establish a cursor into the table, and process
individual rows in the table, SQL provides the following sequence of statements:
1. DECLARE CURSOR establishes a name for the cursor and specifies the query to
perform.
2. OPEN executes the query, builds the results table, and positions the cursor at
the start of the table.
144 INTERBASE 6
SELECTING MULTIPLE ROWS
3. FETCH retrieves a single row at a time from the results table into host variables
for program processing.
4. CLOSE releases system resources when all rows are retrieved.
IMPORTANT To select data from a table, a user must have SELECT privilege for a table, or a stored
procedure invoked by the user’s application must have SELECT privilege for it.
Declaring a cursor
To declare a cursor and specify rows of data to retrieve, use the DECLARE
CURSOR statement. DECLARE CURSOR is a descriptive, non-executable statement. InterBase
uses the information in the statement to prepare system resources for the cursor when it
is opened, but does not actually perform the query. Because DECLARE CURSOR is
non-executable, SQLCODE is not assigned when this statement is used.
The syntax for DECLARE CURSOR is:
DECLARE cursorname CURSOR FOR
SELECT <col> [, <col> ...]
FROM table [, <table> ...]
WHERE <search_condition>
[GROUP BY col [, col ...]]
[HAVING <search_condition>]
[ORDER BY col [ASC | DESC] [, col ...] [ASC | DESC]
| FOR UPDATE OF col [, col ...]];
The cursorname is used in subsequent OPEN, FETCH, and CLOSE statements to identify the
active cursor.
With the following exceptions, the SELECT statement inside a DECLARE
CURSOR is similar to a stand-alone SELECT:
g A SELECT in a DECLARE CURSOR cannot include an INTO clause.
g A SELECT in a DECLARE CURSOR can optionally include either an ORDER BY clause or a FOR
UPDATE clause.
For example, the following statement declares a cursor:
EXEC SQL
DECLARE TO_BE_HIRED CURSOR FOR
SELECT D.DEPARTMENT, D.LOCATION, P.DEPARTMENT
FROM DEPARTMENT D, DEPARTMENT P
WHERE D.MNGR_NO IS NULL
AND D.HEAD_DEPT = P.DEPT_NO;
If a column list after FOR UPDATE is omitted, all columns retrieved for each row may be
updated. For example, the following query enables updating for two columns:
EXEC SQL
DECLARE H CURSOR FOR
SELECT CUST_NAME CUST_NO
FROM CUSTOMER
WHERE ON_HOLD = ’*’;
For more information about updating columns through a cursor, see “Updating multiple
rows” on page 171.
Opening a cursor
Before data selected by a cursor can be accessed, the cursor must be opened with the
OPEN statement. OPEN activates the cursor and builds a results table. It builds the results
table based on the selection criteria specified in the DECLARE CURSOR statement. The rows
in the results table comprise the active set of the cursor.
For example, the following statement opens a previously declared cursor called
DEPT_EMP:
EXEC SQL
OPEN DEPT_EMP;
When InterBase executes the OPEN statement, the cursor is positioned at the start of the
first row in the results table.
146 INTERBASE 6
SELECTING MULTIPLE ROWS
IMPORTANT In dynamic SQL (DSQL) multi-row select processing, a different FETCH syntax is used.
For more information about retrieving multiple rows in DSQL, see “Fetching rows with
a DSQL cursor” on page 154.
For example, the following statement retrieves a row from the results table for the
DEPT_EMP cursor, and copies its column values into the host-language variables,
deptname, lname, and fname:
EXEC SQL
FETCH DEPT_EMP
INTO :deptname, :lname, :fname;
To process each row in a results table in the same manner, enclose the FETCH statement
in a host-language looping construct. For example, the following C code fetches and
prints each row defined for the DEPT_EMP cursor:
. . .
EXEC SQL
FETCH DEPT_EMP
INTO :deptname, :lname, :fname;
while (!SQLCODE)
{
printf("%s %s works in the %s department.\n", fname,
lname, deptname);
EXEC SQL
FETCH DEPT_EMP
INTO :deptname, :lname, :fname;
}
EXEC SQL
CLOSE DEPT_EMP;
. . .
Every FETCH statement should be tested to see if the end of the active set is reached. The
previous example operates in the context of a while loop that continues processing as
long as SQLCODE is zero. If SQLCODE is 100, it indicates that there are no more rows to
retrieve. If SQLCODE is less than zero, it indicates that an error occurred.
Often, the space between the variable that receives the actual contents of a
column and the variable that holds the status of the NULL value flag is also omitted:
FETCH GETCITY INTO :department, :manager:missing_manager;
Note While InterBase enforces the SQL requirement that the number of host variables in
a FETCH must equal the number of columns specified in DECLARE CURSOR, indicator
variables in a FETCH statement are not counted toward the column count.
148 INTERBASE 6
SELECTING MULTIPLE ROWS
Programs can check for the end of the active set by examining SQLCODE, which is set to
100 to indicate there are no more rows to retrieve.
main ()
{
EXEC SQL
WHENEVER SQLERROR GO TO abend;
EXEC SQL
DECLARE DEPT_EMP CURSOR FOR
SELECT DEPARTMENT, LAST_NAME, FIRST_NAME
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DEPT_NO = E.DEPT_NO
ORDER BY DEPARTMENT, LAST_NAME, FIRST_NAME;
EXEC SQL
OPEN DEPT_EMP;
EXEC SQL
FETCH DEPT_EMP
INTO :deptname, :lname, :fname;
while (!SQLCODE)
{
printf("%s %s works in the %s department.\n",fname,
lname, deptname);
EXEC SQL
FETCH DEPT_EMP
INTO :deptname, :lname, :fname;
}
EXEC SQL
CLOSE DEPT_EMP;
exit();
abend:
if (SQLCODE)
{
isc_print_sqlerror();
EXEC SQL
ROLLBACK;
EXEC SQL
CLOSE_DEPT_EMP;
EXEC SQL
DISCONNECT ALL;
exit(1)
}
else
{
EXEC SQL
COMMIT;
EXEC SQL
150 INTERBASE 6
SELECTING MULTIPLE ROWS
DISCONNECT ALL;
exit()
}
}
Note To determine if a column has a NULL value, use an indicator variable. For more
information about indicator variables, see “Retrieving indicator status” on page 148.
A direct query on a column containing a NULL value returns zero for numbers, blanks for
characters, and 17 November 1858 for dates. For example, the following cursor
declaration retrieves all department budgets, even those with NULL values, which are
reported as zero:
EXEC SQL
DECLARE ALL_BUDGETS CURSOR FOR
SELECT DEPARTMENT, BUDGET
FROM DEPARTMENT
ORDER BY BUDGET DESCENDING;
g NULL values are skipped by all aggregate operations, except for COUNT(*).
g NULL values cannot be elicited by a negated test in a search condition.
g NULL values cannot satisfy a join condition.
NULL values can be tested in comparisons. If a value on either side of a comparison
operator is NULL, the result of the comparison is Unknown.
For the Boolean operators (NOT, AND, and OR), the following considerations are made:
g NULL values with NOT always returns Unknown.
g NULL values with AND return Unknown unless one operand for AND is false. In this latter
case, False is returned.
g NULL values with OR return Unknown unless one operand for OR is true. In this latter case,
True is returned.
For information about defining alternate NULL values, see the Data Definition Guide.
A view can be a join. Views can also be used in joins, themselves, in place of tables. For
more information about views in joins, see “Joining tables” on page 155.
152 INTERBASE 6
SELECTING MULTIPLE ROWS IN DSQL
EXEC SQL
END DECLARE SECTION;
. . .
printf("Enter query: "); /* prompt for query from user */
gets(querystring); /* get the string, store in querystring */
. . .
EXEC SQL
PREPARE QUERY INTO OutputSqlda FROM :querystring;
. . .
EXEC SQL
DECLARE C CURSOR FOR QUERY;
For more information about creating and filling XSQLDA structures, and preparing DSQL
queries with PREPARE, see Chapter 13, “Using Dynamic SQL.”
For example, the following statement opens the cursor, C, using the XSQLDA, InputSqlda:
EXEC SQL
OPEN C USING DESCRIPTOR InputSqlda;
For example, the following C code fragment declares XSQLDA structures for input and
output, and illustrates how the output structure is used in a FETCH statement:
. . .
XSQLDA *InputSqlda, *OutputSqlda;
. . .
154 INTERBASE 6
JOINING TABLES
EXEC SQL
FETCH C USING DESCRIPTOR OutputSqlda;
. . .
For more information about creating and filling XSQLDA structures, and preparing DSQL
queries with PREPARE, see Chapter 13, “Using Dynamic SQL.”
Joining tables
Joins enable retrieval of data from two or more tables in a database with a single SELECT.
The tables from which data is to be extracted are listed in the FROM clause. Optional
syntax in the FROM clause can reduce the number of rows returned, and additional WHERE
clause syntax can further reduce the number of rows returned.
From the information in a SELECT that describes a join, InterBase builds a table that
contains the results of the join operation, the results table, sometimes also called a
dynamic or virtual table.
InterBase supports two types of joins:
g Inner joins link rows in tables based on specified join conditions, and return only those
rows that match the join conditions. There are three types of inner joins:
· Equi-joins link rows based on common values or equality relationships in the join
columns.
· Joins that link rows based on comparisons other than equality in the join columns.
There is not an officially recognized name for these types of joins, but for simplicity’s
sake they may be categorized as comparative joins, or non-equi-joins.
· Reflexive or self-joins, compare values within a column of a single table.
g Outer joins link rows in tables based on specified join conditions and return both rows
that match the join conditions, and all other rows from one or more tables even if they
do not match the join condition.
The most commonly used joins are inner joins, because they both restrict the data
returned, and show a clear relationship between two or more tables. Outer joins,
however, are useful for viewing joined rows against a background of rows that do not
meet the join conditions.
IMPORTANT If a joined column contains a NULL value for a given row, InterBase does not include that
row in the results table unless performing an outer join.
156 INTERBASE 6
JOINING TABLES
The join is explicitly declared in the FROM clause using the JOIN keyword. The table
reference appearing to the left of the JOIN keyword is called the left table, while the table
to the right of the JOIN is called the right table. The conditions of the join—the columns
from each table—are stated in the ON clause. The WHERE clause contains search
conditions that limit the number of rows returned. For example, using the new join
syntax, the previously described query can be rewritten as:
EXEC SQL
DECLARE BIG_SAL CURSOR FOR
SELECT D.DEPARTMENT, D.MNGR_NO, E.SALARY
FROM DEPARTMENT D INNER JOIN EMPLOYEE E
ON D.MNGR_NO = E.EMP_NO
WHERE E.SALARY*2 > (SELECT SUM(S.SALARY) FROM EMPLOYEE S
WHERE D.DEPT_NO = S.DEPT_NO)
ORDER BY D.DEPARTMENT;
The new join syntax offers several advantages. An explicit join declaration makes the
intention of the program clear when reading its source code.
The ON clause contains join conditions. The WHERE clause can contains conditions that
restrict which rows are returned.
The FROM clause also permits the use of table references, which can be used to construct
joins between three or more tables. For more information about nested joins, see “Using
nested joins” on page 161.
4 Creating equi-joins
An inner join that matches values in join columns is called an equi-join. Equi-joins are
among the most common join operations. The ON clause in an equi-join always takes the
form:
ON t1.column = t2.column
For example, the following join returns a list of cities around the world if the capital cities
also appear in the CITIES table, and also returns the populations of those cities:
EXEC SQL
DECLARE CAPPOP CURSOR FOR
SELECT COU.NAME, COU.CAPITAL, CIT.POPULATION
FROM COUNTRIES COU JOIN CITIES CIT ON CIT.NAME = COU.CAPITAL
WHERE COU.CAPITAL NOT NULL
ORDER BY COU.NAME;
In this example, the ON clause specifies that the CITIES table must contain a city name
that matches a capital name in the COUNTRIES table if a row is to be returned. Note that
the WHERE clause restricts rows retrieved from the COUNTRIES table to those where the
CAPITAL column contains a value.
where operator is a valid comparison operator. For a list of valid comparison operators,
see “Using comparison operators in expressions” on page 114.
For example, the following join returns information about provinces in Canada that are
larger than the state of Alaska in the United States:
EXEC SQL
DECLARE BIGPROVINCE CURSOR FOR
SELECT S.STATE_NAME, S.AREA, P.PROVINCE_NAME, P.AREA
FROM STATES S JOIN PROVINCE P ON P.AREA > S.AREA AND
P.COUNTRY = ’Canada’
WHERE S.STATE_NAME = ’Alaska’;
In this example, the first comparison operator in the ON clause tests to see if the area of
a province is greater than the area of any state (the WHERE clause restricts final output to
display only information for provinces that are larger in area than the state of Alaska).
4 Creating self-joins
A self-join is an inner join where a table is joined to itself to correlate columns of data.
For example, the RIVERS table lists rivers by name, and, for each river, lists the river into
which it flows. Not all rivers, of course, flow into other rivers. To discover which rivers
flow into other rivers, and what their names are, the
RIVERS table must be joined to itself:
EXEC SQL
DECLARE RIVERSTORIVERS CURSOR FOR
SELECT R1.RIVER, R2.RIVER
FROM RIVERS R1 JOIN RIVERS R2 ON R2.OUTFLOW = R1.RIVER
ORDER BY R1.RIVER, R2.SOURCE;
158 INTERBASE 6
JOINING TABLES
As this example illustrates, when a table is joined to itself, each invocation of the table
must be assigned a unique correlation name (R1 and R2 are correlation names in the
example). For more information about assigning and using correlation names, see
“Declaring and using correlation names” on page 134.
Outer join syntax requires that you specify the type of join to perform. There are three
possibilities:
g A left outer join retrieves all rows from the left table in a join, and retrieves any rows from
the right table that match the search condition specified in the ON clause.
g A right outer join retrieves all rows from the right table in a join, and retrieves any rows
from the left table that match the search condition specified in the ON clause.
g A full outer join retrieves all rows from both the left and right tables in a join regardless
of the search condition specified in the ON clause.
Outer joins are useful for comparing a subset of data to the background of all data from
which it is retrieved. For example, when listing those countries which contain the sources
of rivers, it may be interesting to see those countries which are not the sources of rivers
as well.
The ON clause enables join search conditions to be expressed in the FROM clause. The
search condition that follows the ON clause is the only place where retrieval of rows can
be restricted based on columns appearing in the right table. The WHERE clause can be
used to further restrict rows based solely on columns in the left (outer) table.
Tip Most right outer joins can be rewritten as left outer joins by reversing the order in which
tables are listed.
160 INTERBASE 6
USING SUBQUERIES
Note In most databases where tables share similar or related information, triggers are
usually created to ensure that all tables are updated with shared information. For more
information about triggers, see the Data Definition Guide.
For more information about left joins, see “Using outer joins” on page 159.
Using subqueries
A subquery is a parenthetical SELECT statement nested inside the WHERE clause of another
SELECT statement, where it functions as a search condition to restrict the number of rows
returned by the outer, or parent, query. A subquery can refer to the same table or tables
as its parent query, or to other tables.
The elementary syntax for a subquery is:
SELECT [DISTINCT] col [, col ...]
FROM <tableref> [, <tableref> ...]
WHERE {expression {[NOT] IN | comparison_operator}
| [NOT] EXISTS} (SELECT [DISTINCT] col [, col ...]
FROM <tableref> [, <tableref> ...]
WHERE <search_condition>);
Because a subquery is a search condition, it is usually evaluated before its parent query,
which then uses the result to determine whether or not a row qualifies for retrieval. The
only exception is the correlated subquery, where the parent query provides values for the
subquery to evaluate. For more information about correlated subqueries, see
“Correlated subqueries” on page 163.
A subquery determines the search condition for a parent’s WHERE clause in one of the
following ways:
g Produces a list of values for evaluation by an IN operator in the parent query’s WHERE
clause, or where a comparison operator is modified by the ALL, ANY, or SOME operators.
g Returns a single value for use with a comparison operator.
g Tests whether or not data meets conditions specified by an EXISTS operator in the parent
query’s WHERE clause.
Subqueries can be nested within other subqueries as search conditions, establishing a
chain of parent/child queries.
Simple subqueries
A subquery is especially useful for extracting data from a single table when a self-join is
inadequate. For example, it is impossible to retrieve a list of those countries with a larger
than average area by joining the COUNTRIES table to itself. A subquery, however, can easily
return that information.
EXEC SQL
DECLARE LARGECOUNTRIES CURSOR FOR
SELECT COUNTRY, AREA
FROM COUNTRIES
WHERE AREA > (SELECT AVG(AREA) FROM COUNTRIES);
ORDER BY AREA;
In this example, both the query and subquery refer to the same table. Queries and
subqueries can refer to different tables, too. For example, the following query refers to
the CITIES table, and includes a subquery that refers to the COUNTRIES table:
EXEC SQL
DECLARE EUROCAPPOP CURSOR FOR
SELECT CIT.CITY, CIT.POPULATION
FROM CITIES CIT
WHERE CIT.CITY IN (SELECT COU.CAPITAL FROM COUNTRIES COU
WHERE COU.CONTINENT = ’Europe’)
ORDER BY CIT.CITY;
162 INTERBASE 6
USING SUBQUERIES
This example uses correlation names to distinguish between tables even though the
query and subquery reference separate tables. Correlation names are only necessary
when both a query and subquery refer to the same tables and those tables share column
names, but it is good programming practice to use them. For more information about
using correlation names, see “Declaring and using correlation names” on page 134.
Correlated subqueries
A correlated subquery is a subquery that depends on its parent query for the values it
evaluates. Because each row evaluated by the parent query is potentially different, the
subquery is executed once for each row presented to it by the parent query.
For example, the following query lists each country for which there are three or more
cities stored in the CITIES table. For each row in the COUNTRIES table, a country name is
retrieved in the parent query, then used in the comparison operation in the subquery’s
WHERE clause to verify if a city in the CITIES table should be counted by the COUNT()
function. If COUNT() exceeds 2 for a row, the row is retrieved.
EXEC SQL
DECLARE TRICITIES CURSOR FOR
SELECT COUNTRY
FROM COUNTRIES COU
WHERE 3 <= (SELECT COUNT (*)
FROM CITIES CIT
WHERE CIT.CITY = COU.CAPITAL);
Simple and correlated subqueries can be nested and mixed to build complex queries. For
example, the following query retrieves the country name, capital city, and largest city of
countries whose areas are larger than the average area of countries that have at least one
city within 30 meters of sea level:
EXEC SQL
DECLARE SEACOUNTRIES CURSOR FOR
SELECT CO1.COUNTRY, C01.CAPITAL, CI1.CITY
FROM COUNTRIES C01, CITIES CI1
WHERE CO1.COUNTRY = CI1.COUNTRY AND CI1.POPULATION =
(SELECT MAX(CI2.POPULATION)
FROM CITIES CI2 WHERE CI2.COUNTRY = CI1.COUNTRY)
AND CO1.AREA >
(SELECT AVG (CO2.AREA)
FROM COUNTRIES C02 WHERE EXISTS
(SELECT *
FROM CITIES CI3 WHERE CI3.COUNTRY = CO2.COUNTRY
AND CI3.ALTITUDE <= 30));
When a table is separately searched by queries and subqueries, as in this example, each
invocation of the table must establish a separate correlation name for the table. Using
correlation names is the only method to assure that column references are associated
with appropriate instances of their tables. For more information about correlation names,
see “Declaring and using correlation names” on page 134.
Inserting data
New rows of data are added to one table at a time with the INSERT statement. To insert
data, a user or stored procedure must have INSERT privilege for a table.
The INSERT statement enables data insertion from two different sources:
g A VALUES clause that contains a list of values to add, either through hard-coded values, or
host-language variables.
g A SELECT statement that retrieves values from one table to add to another.
The syntax of INSERT is as follows:
INSERT [TRANSACTION name] INTO table [(col [, col ...])]
{VALUES (<val>[:ind] [, <val>[:ind] ...])
| SELECT <clause>};
The list of columns into which to insert values is optional in DSQL applications. If it is
omitted, then values are inserted into a table’s columns according to the order in which
the columns were created. If there are more columns than values, the remaining columns
are filled with zeros.
164 INTERBASE 6
INSERTING DATA
Because the DEPARTMENT table contains additional columns not specified in the INSERT,
NULL values are assigned to the missing fields.
The following C code example prompts a user for information to add to the DEPARTMENT
table, and inserts those values from host variables:
. . .
EXEC SQL
BEGIN DECLARE SECTION;
char department[26], dept_no[16];
int dept_num;
EXEC SQL
END DECLARE SECTION;
. . .
printf("Enter name of department: ");
gets(department);
printf("\nEnter department number: ");
dept_num = atoi(gets(dept_no));
EXEC SQL
INSERT INTO COUNTRIES (DEPT_NO, DEPARTMENT)
VALUES (:dept_num, :department);
When host variables are used in the values list, they must be preceded by colons (:) so
that SQL can distinguish them from table column names.
The assignments in the SELECT can include arithmetic operations. For example, suppose
an application keeps track of employees by using an employee number. When a new
employee is hired, the following statement inserts a new employee row into the EMPLOYEE
table, and assigns a new employee number to the row by using a SELECT statement to find
the current maximum employee number and adding one to it. It also reads values for
LAST_NAME and FIRST_NAME from the host variables, lastname, and firstname.
EXEC SQL
INSERT INTO EMPLOYEE (EMP_NO, LAST_NAME, FIRST_NAME)
SELECT (MAX(EMP_NO) + 1, :lastname, :firstname)
FROM EMPLOYEE;
4 Ignoring a column
A NULL value is assigned to any column that is not explicitly specified in an INTO clause.
When InterBase encounters an unreferenced column during insertion, it sets a flag for
the column indicating that its value is unknown. For example, the DEPARTMENT table
contains several columns, among them HEAD_DEPT, MNGR_NO, and BUDGET. The
following INSERT does not provide values for these columns:
EXEC SQL
INSERT INTO DEPARTMENT (DEPT_NO, DEPARTMENT)
VALUES (:newdept_no, :newdept_name);
Because HEAD_DEPT, MNGR_NO, and BUDGET are not specified, InterBase sets the NULL
value flag for each of these columns.
Note If a column is added to an existing table, InterBase sets a NULL value flag for all
existing rows in the table.
166 INTERBASE 6
INSERTING DATA
3. Associate the indicator variable with the host variable in the INSERT statement
using the following syntax:
INSERT INTO table (<col> [, <col> ...])
VALUES (:variable [INDICATOR] :indicator
[, :variable [INDICATOR] :indicator ...]);
For example, the following C code fragment prompts the user for the name of a
department, the department number, and a budget for the department. It tests that the
user has entered a budget. If not, it sets the indicator variable, bi, to –1. Otherwise, it sets
bi to 0. Finally, the program INSERTS the information into the DEPARTMENT table. If the
indicator variable is –1, then no actual data is stored in the BUDGET column, but a flag is
set for the column indicating that the value is NULL
. . .
EXEC SQL
BEGIN DECLARE SECTION;
short bi; /* indicator variable declaration */
char department[26], dept_no_ascii[26], budget_ascii[26];
long num_val; /* host variable for inserting budget */
short dept_no;
EXEC SQL
END DECLARE SECTION;
. . .
printf("Enter new department name: ");
gets(cidepartment);
printf("\nEnter department number: ");
gets(dept_no_ascii);
printf("\nEnter department’s budget: ");
gets(budget_ascii);
if (budget_ascii = "")
{
bi = -1; num_val = 0;
}
else
{
bi = 0;
num_val = atoi(budget_ascii);
}
dept_no = atoi(dept_no_ascii);
EXEC SQL
INSERT INTO DEPARTMENT (DEPARTMENT, DEPT_NO, BUDGET)
VALUES (:department, :dept_no, :num_val INDICATOR :bi);
. . .
Indicator status can also be determined for data retrieved from a table. For information
about trapping NULL values retrieved from a table, see “Retrieving indicator status” on
page 148.
168 INTERBASE 6
INSERTING DATA
Because PART_DEPT references a single table, DEPARTMENT, new data can be inserted for
the DEPARTMENT, DEPT_NO, and BUDGET columns. The WITH CHECK OPTION assures that
all values entered through the view fall within ranges of values that can be selected by
this view. For example, the following statement inserts a new row for the Publications
department through the PART_DEPT view:
EXEC SQL
INSERT INTO PART_DEPT (DEPARTMENT, DEPT_NO, BUDGET)
VALUES (’Publications’, ’7735’, 1500000);
InterBase inserts NULL values for all other columns in the DEPARTMENT table that are not
available directly through the view.
For information about creating a view, see Chapter 5, “Working with Data Definition
Statements.” For the complete syntax of CREATE VIEW, see the Language Reference.
Note See the chapter on triggers in the Data Definition Guide for tips on using triggers
to update non-updatable views.
g Each transaction is first named with a SET TRANSACTION statement. For a complete
discussion of transaction handling and naming, see Chapter 4, “Working with
Transactions.”
g Each data manipulation statement (SELECT, INSERT, UPDATE, DELETE, DECLARE, OPEN,
FETCH, and CLOSE) specifies a TRANSACTION clause that identifies the name of the
transaction under which it operates.
g SQL statements are not dynamic (DSQL). DSQL does not support user-specified
transaction names.
With INSERT, the TRANSACTION clause intervenes between the INSERT keyword and the list
of columns to insert, as in the following syntax fragment:
INSERT TRANSACTION name INTO table (col [, col ...])
Updating data
To change values for existing rows of data in a table, use the UPDATE statement. To update
a table, a user or procedure must have UPDATE privilege for it. The syntax of UPDATE is:
UPDATE [TRANSACTION name] table
SET col = <assignment> [, col = <assignment> ...]
WHERE <search_condition> | WHERE CURRENT OF cursorname;
UPDATE changes values for columns specified in the SET clause; columns not listed in the
SET clause are not changed. A single UPDATE statement can be used to modify any
number of rows in a table. For example, the following statement modifies a single row:
EXEC SQL
UPDATE DEPARTMENT
SET DEPARTMENT = ’Publications’
WHERE DEPARTMENT = ’Documentation’;
170 INTERBASE 6
UPDATING DATA
The WHERE clause in this example targets a single row for update. If the same change
should be propagated to a number of rows in a table, the WHERE clause can be more
general. For example, to change all occurrences of “Documentation” to “Publications” for
all departments in the DEPARTMENT table where DEPARTMENT equals “Documentation,”
the UPDATE statement would be as follows:
EXEC SQL
UPDATE DEPARTMENT
SET DEPARTMENT = ’Publications’
WHERE DEPARTMENT = ’Documentation’;
Using UPDATE to make the same modification to a number of rows is sometimes called a
mass update, or a searched update.
The WHERE clause in an UPDATE statement can contain a subquery that references one or
more other tables. For a complete discussion of subqueries, see “Using subqueries” on
page 161.
172 INTERBASE 6
UPDATING DATA
EXEC SQL
FETCH CHANGEPOP INTO :country;
if (SQLCODE && (SQLCODE != 100))
{
isc_print_sqlerr(SQLCODE, isc_status);
EXEC SQL
ROLLBACK RELEASE;
exit(1);
}
}
EXEC SQL
COMMIT RELEASE;
}
IMPORTANT Using FOR UPDATE with a cursor causes rows to be fetched from the database one at a
time. If FOR UPDATE is omitted, rows are fetched in batches.
174 INTERBASE 6
UPDATING DATA
Because PART_DEPT references a single table, data can be updated for the columns named
in the view. The WITH CHECK OPTION assures that all values entered through the view fall
within ranges prescribed for each column when the DEPARTMENT table was created. For
example, the following statement updates the budget of the Publications department
through the PART_DEPT view:
EXEC SQL
UPDATE PART_DEPT
SET BUDGET = 2505700
WHERE DEPARTMENT = ’Publications’;
For information about creating a view, see Chapter 5, “Working with Data Definition
Statements.” For the complete syntax of CREATE VIEW, see the Language Reference.
Note See the chapter on triggers in the Data Definition Guide for tips on using triggers
to update non-updatable views.
Deleting data
To remove rows of data from a table, use the DELETE statement. To delete rows a user or
procedure must have DELETE privilege for the table.
The syntax of DELETE is:
DELETE [TRANSACTION name] FROM table
WHERE <search_condition> | WHERE CURRENT OF cursorname;
DELETE irretrievably removes entire rows from the table specified in the FROM clause,
regardless of each column’s datatype.
A single DELETE can be used to remove any number of rows in a table. For example, the
following statement removes the single row containing “Channel Marketing” from the
DEPARTMENT table:
EXEC SQL
DELETE FROM DEPARTMENT
WHERE DEPARTMENT = ’Channel Marketing’;
The WHERE clause in this example targets a single row for update. If the same deletion
criteria apply to a number of rows in a table, the WHERE clause can be more general. For
example, to remove all rows from the DEPARTMENT table with BUDGET values
< $1,000,000, the DELETE statement would be as follows:
EXEC SQL
DELETE FROM DEPARTMENT
WHERE BUDGET < 1000000;
176 INTERBASE 6
DELETING DATA
}
}
178 INTERBASE 6
DELETING DATA
EXEC SQL
FETCH DELETECITY INTO :cityname;
if (SQLCODE)
{
if (SQLCODE == 100)
{
printf(’Deletions complete.’);
EXEC SQL
COMMIT;
EXEC SQL
CLOSE DELETECITY;
EXEC SQL
DISCONNECT ALL:
}
isc_print_sqlerr(SQLCODE, isc_status);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT ALL;
exit(1);
}
printf("\nDelete %s (Y/N)?", cityname);
gets(response);
if(response[0] == ’Y’ || response == ’y’)
{
EXEC SQL
DELETE FROM CITIES
WHERE CURRENT OF DELETECITY;
if(SQLCODE && (SQLCODE != 100))
{
isc_print_sqlerr(SQLCODE, isc_status);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT;
exit(1);
}
}
}
For information about creating a view, see Chapter 5, “Working with Data Definition
Statements.” For CREATE VIEW syntax, see the Language Reference.
Note See the chapter on triggers in the Data Definition Guide for tips on using triggers
to delete through non-updatable views.
180 INTERBASE 6
DELETING DATA
182 INTERBASE 6
CHAPTER
The chapter also discusses how to use the CAST() function to translate DATE, TIME, and
TIMESTAMP datatypes into each other or into CHAR datatypes and back again, and how to
use the DATE literals, NOW and TODAY when selecting and inserting dates.
To create host-language time structures in languages other than C and C++, see the
host-language reference manual.
2. Create a host variable of type ISC_TIMESTAMP. For example, the host-variable
declaration might look like this:
ISC_TIMESTAMP hire_date;
The ISC_TIMESTAMP structure is automatically declared for programs when they are
preprocessed with gpre, but the programmer must declare actual host-language
variables of type ISC_TIMESTAMP.
3. Retrieve a timestamp from a table into the ISC_TIMESTAMP variable. For
example,
EXEC SQL
SELECT LAST_NAME, FIRST_NAME, DATE_OF_HIRE
INTO :lname, :fname, :hire_date
FROM EMPLOYEE
WHERE LAST_NAME = ’Smith’ AND FIRST_NAME = ’Margaret’;
184 INTERBASE 6
INSERTING DATES AND TIMES
Convert the isc_timestamp variable into a numeric Unix format with the InterBase
function, isc_decode_timestamp(). This function is automatically declared for
programs when they are preprocessed with gpre. isc_decode_timestamp() requires
two parameters: the address of the isc_timestamp host-language variable, and the
address of the struct tm host-language variable. For example, the following code
fragment coverts hire_date to hire_time:
isc_decode_timestamp(&hire_date, &hire_time);
To create host-language time structures in languages other than C and C++, see the
host-language reference manual.
2. Create a host variable of type ISC_TIMESTAMP, for use by InterBase. For
example, the host-variable declaration might look like this:
ISC_TIMESTAMP mydate;
The ISC_TIMESTAMP structure is automatically declared for programs when they are
preprocessed with gpre, but the programmer must declare actual host-language
variables of type ISC_TIMESTAMP.
3. Put date information into hire_time.
186 INTERBASE 6
USING CAST( ) TO CONVERT DATES AND TIMES
Typically, CAST() is used in the WHERE clause to compare different datatypes. The syntax
for CAST() is:
CAST (<value> AS <datatype>)
In the next example, CAST() translates a DATE datatype into a CHAR datatype:
… WHERE CAST(HIRE_DATE AS CHAR) = INTERVIEW_DATE;
CAST() also can be used to compare columns with different datatypes in the same table,
or across tables.
The following two sections show the possible conversions to and from datetime (DATE,
TIME, and TIMESTAMP) datatypes and other SQL datatypes.
For more information about CAST(), see Chapter 6, “Working with Data.”
VARCHAR(n) Succeeds it the string is in Succeeds it the string is in Succeeds it the string is in
CHAR(n) the following format: the following format: the following format:
CSTRING(n)
YYYY-MM-DD YYYY-MM-DD HH:MM:SS.thou
HH:MM:SS.thou
BLOB Error Error Error
TABLE 7.1 Casting from SQL datatypes to datetime datatypes
188 INTERBASE 6
USING DATE LITERALS
In INSERT and UPDATE, ’TIMESTAMP’ and ’DATE’ can be used to enter date and time values
instead of relying on isc calls to convert C dates to InterBase dates:
EXEC SQL
INSERT INTO CROSS_RATE VALUES(:from, :to, :rate, ’NOW’);
EXEC SQL
UPDATE CROSS_RATE
SET CONV_RATE = 1.75,
SET UPDATE_DATE = ’TIMESTAMP’
WHERE FROM_CURRENCY = ’POUND’ AND TO_CURRENCT = ’DOLLAR’
AND UPDATE_DATE < ’TODAY’;
190 INTERBASE 6
CHAPTER
What is a Blob?
A Blob is a dynamically sizable datatype that has no specified size and encoding. You can
use a Blob to store large amounts of data of various types, including:
g Bitmapped images
g Vector drawings
g Sounds, video segments, and other multimedia information
g Text and data, including book-length documents
Data stored in the Blob datatype can be manipulated in most of the same ways as data
stored in any other datatype. InterBase stores Blob data inside the database, in contrast
to similar other systems that store pointers to non-database files. For each Blob, there is
a unique identification handle in the appropriate table to point to the database location
of the Blob. By maintaining the Blob data within the database, InterBase improves data
management and access.
The combination of true database management of Blob data and support for a variety of
datatypes makes InterBase Blob support ideal for transaction-intensive multimedia
applications. For example, InterBase is an excellent platform for interactive kiosk
applications that might provide hundreds or thousands of product descriptions,
photographs, and video clips, in addition to point-of-sale and order processing
capabilities.
192 INTERBASE 6
HOW ARE BLOB DATA STORED?
Blob subtypes
Although you manage Blob data in the same way as other datatypes, InterBase provides
more flexible datatyping rules for Blob data. Because there are many native datatypes that
you can define as Blob data, InterBase treats them somewhat generically and allows you
to define your own datatype, known as a subtype. Also, InterBase provides seven standard
subtypes with which you can characterize Blob data:
Blob
subtype Description
0 Unstructured, generally applied to binary data or data of an indeterminate type
1 Text
2 Binary language representation (BLR)
3 Access control list
4 (Reserved for future use)
5 Encoded description of a table’s current metadata
6 Description of multi-database transaction that finished irregularly
TABLE 8.1 Blob subtypes defined by InterBase
To specify both a default segment length and a subtype when creating a Blob column,
use the SEGMENT SIZE option after the SUB_TYPE option. For example:
EXEC SQL CREATE TABLE TABLE2
(
BLOB1 BLOB SUB_TYPE 1 SEGMENT SIZE 100;
);
The only rule InterBase enforces over these user-defined subtypes is that, when
converting a Blob from one subtype to another, those subtypes must be compatible.
InterBase does not otherwise enforce subtype integrity.
You define Blob columns the same way you define non-Blob columns.
The following SQL code creates a table with a Blob column called PROJ_DESC. It sets the
subtype parameter to 1, which denotes a TEXT Blob, and sets the segment size to 80 bytes:
CREATE TABLE PROJECT
(
PROJ_ID PROJNO NOT NULL,
PROJ_NAME VARCHAR(20) NOT NULL UNIQUE,
PROJ_DESC BLOB SUBTYPE 1 SEGMENT SIZE 80,
TEAM_LEADER EMPNO,
PRODUCT PRODTYPE,
...
);
The following diagram shows the relationship between a Blob column containing a Blob
ID and the Blob data referenced by the Blob ID:
194 INTERBASE 6
HOW ARE BLOB DATA STORED?
Blob
column
Table row … Blob ID …
Rather than store Blob data directly in the table, InterBase stores a Blob ID in each row
of the table. The Blob ID, a unique number, points to the first segment of the Blob data
that is stored elsewhere in the database, in a series of segments. When an application
creates a Blob, it must write data to that Blob a segment at a time. Similarly, when an
application reads of Blob, it reads a segment at a time. Because most Blob data are large
objects, most Blob management is performed with loops in the application code.
InterBase uses the segment length setting to determine the size of an internal buffer to
which it writes Blob segment data. Normally, you should not attempt to write segments
larger than the segment length you defined in the table; doing so may result in a buffer
overflow and possible memory corruption.
Specifying a segment size of n guarantees that no more than n number of bytes are read
or written in a single Blob operation. With some types of operations, for instance, with
SELECT, INSERT, and UPDATE operations, you can read or write Blob segments of varying
length.
In the following example of an INSERT CURSOR statement, specify the segment length in
a host language variable, segment_length, as follows:
EXEC SQL
INSERT CURSOR BCINS VALUES (:write_segment_buffer
INDICATOR :segment_length);
For more information about the syntax of the INSERT CURSOR statement, see the Language
Reference.
Note By overriding the segment length setting, you affect only the segment size for the
cursor, not for the column, or for other cursors. Other cursors using the same Blob
column maintain the original segment size that was defined in the column definition, or
can specify their own overrides.
The segment length setting does not affect InterBase system performance. Choose the
segment length most convenient for the specific application. The largest possible segment
length is 65,535 bytes (64K).
196 INTERBASE 6
ACCESSING BLOB DATA WITH SQL
3. Declare a Blob read cursor. A Blob read cursor is a special cursor used for
reading Blob segments:
EXEC SQL
DECLARE BC CURSOR FOR
READ Blob GUIDEBOOK
FROM TOURISM;
The segment length of the GUIDEBOOK Blob column is defined as 60, so Blob cursor,
BC, reads a maximum of 60 bytes at a time.
To override the segment length specified in the database schema for GUIDEBOOK,
use the MAXIMUM_SEGMENT option. For example, the following code restricts each
Blob read operation to a maximum of 40 bytes, and SQLCODE is set to 101 to indicate
when only a portion of a segment has been read:
EXEC SQL
DECLARE BC CURSOR FOR
READ Blob GUIDEBOOK
FROM TOURISM
MAXIMUM_SEGMENT 40;
No matter what the segment length setting is, only one segment is read at a time.
4. Open the table cursor and fetch a row of data containing a Blob:
EXEC SQL
OPEN TC;
EXEC SQL
FETCH TC INTO :state, :blob_id;
The FETCH statement fetches the STATE and GUIDEBOOK columns into host variables
state and blob_id, respectively.
5. Open the Blob read cursor using the Blob ID stored in the blob_id variable,
and fetch the first segment of Blob data:
EXEC SQL
OPEN BC USING :blob_id;
EXEC SQL
FETCH BC INTO :blob_segment_buf:blob_seg_len;
When the FETCH operation completes, blob_segment_buf contains the first segment
of the Blob, and blob_seg_len contains the segment’s length, which is the number of
bytes copied into blob_segment_buf.
6. Fetch the remaining segments in a loop. SQLCODE should be checked each
time a fetch is performed. An error code of 100 indicates that all of the Blob
data has been fetched. An error code of 101 indicates that the segment
contains additional data:
while (SQLCODE != 100 || SQLCODE == 101)
{
printf("%*.*s", blob_seg_len, blob_seg_len, blob_segment_buf);
EXEC SQL
FETCH BC INTO :blob_segment_buf:blob_seg_len;
}
InterBase produces an error code of 101 when the length of the segment buffer is less
than the length of a particular segment.
For example, if the length of the segment buffer is 40 and the length of a particular
segment is 60, the first FETCH produces an error code of 101 indicating that data
remains in the segment. The second FETCH reads the remaining 20 bytes of data, and
produces an SQLCODE of 0, indicating that the next segment is ready to be read, or 100
if this was the last segment in the Blob.
1. Close the Blob read cursor:
EXEC SQL
CLOSE BC;
198 INTERBASE 6
ACCESSING BLOB DATA WITH SQL
EXEC SQL
CLOSE TC;
3. Open the Blob insert cursor and specify the host variable in which to store
the Blob ID:
EXEC SQL
OPEN BC INTO :blob_id;
EXEC SQL
INSERT CURSOR BC VALUES (:blob_segment_buf:blob_segment_len);
Repeat these steps in a loop until you have written all Blob segments.
5. Close the Blob insert cursor:
EXEC SQL
CLOSE BC;
6. Use an INSERT statement to insert a new row containing the Blob into the
TOURISM table:
EXEC SQL
INSERT INTO TOURISM (STATE,GUIDEBOOK) VALUES (’CA’,:blob_id);
2. Open the Blob insert cursor and specify the host variable in which to store
the Blob ID:
EXEC SQL
OPEN BC INTO :blob_id;
3. Store the old Blob segment data in the segment buffer blob_segment_buf,
calculate the length of the segment data, perform any modifications to the
data, and use an INSERT CURSOR statement to write the segment:
/* Programmatically read the first/next segment of the old Blob
* segment data into blob_segment_buf; */
EXEC SQL
INSERT CURSOR BC VALUES (:blob_segment_buf:blob_segment_len);
Repeat these steps in a loop until you have written all Blob segments.
4. Close the Blob insert cursor:
200 INTERBASE 6
ACCESSING BLOB DATA WITH SQL
EXEC SQL
CLOSE BC;
5. When you have completed creating the new Blob, issue an UPDATE statement
to replace the old Blob in the table with the new one, as in the following
example:
EXEC SQL UPDATE TOURISM
SET
GUIDEBOOK = :blob_id;
WHERE CURRENT OF TC;
Note The TC table cursor points to a target row established by declaring the cursor and
then fetching the row to update.
To modify a text Blob using this technique, you might read an existing Blob field into a
host-language buffer, modify the data, then write the modified buffer over the existing
field data with an UPDATE statement.
Blob data is not immediately deleted when DELETE is specified. The actual delete
operation occurs when InterBase performs version cleanup. The following code fragment
illustrates how to recover space after deleting a Blob:
EXEC SQL
UPDATE TABLE SET Blob_COLUMN = NULL WHERE ROW = :myrow;
EXEC SQL
COMMIT;
/* wait for all active transactions to finish */
/* force a sweep of the database */
Function Description
isc_blob_default_desc() Loads a Blob descriptor data structure with default information
about a Blob.
isc_blob_gen_bpb() Generates a Blob parameter buffer (BPB) from source and target
Blob descriptors to allow dynamic access to Blob subtype and
character set information.
isc_blob_info() Returns information about an open Blob.
isc_blob_lookup_desc() Looks up and stores into a Blob descriptor the subtype, character
set, and segment size of a Blob.
isc_blob_set_desc() Sets the fields of a Blob descriptor to values specified in parameters
to isc_blob_set_desc().
isc_cancel_blob() Discards a Blob and frees internal storage.
isc_close_blob() Closes an open Blob.
isc_create_blob2() Creates a context for storing a Blob, opens the Blob for write access,
and optionally specifies a filter to be used to translate the Blob data
from one subtype to another.
isc_get_segment() Reads a segment from an open Blob.
isc_open_blob2() Opens an existing Blob for retrieval and optional filtering.
isc_put_segment() Writes a Blob segment.
TABLE 8.2 API Blob calls
For details on using the API calls to access Blob data, see the API Guide.
202 INTERBASE 6
FILTERING BLOB DATA
IMPORTANT Blob filters are available for databases residing on all InterBase server platforms except
NetWare, where Blob filters cannot be created or used.
Tip To convert any non-text subtype to TEXT, declare its FROM subtype as subtype 0 and its
TO subtype as subtype 1.
In the example, the filter’s input subtype is defined as -1 and its output subtype as -2. In
this example, INPUT_TYPE specifies lowercase text and OUTPUT_TYPE specifies uppercase
text. The purpose of filter, SAMPLE, therefore, is to translate Blob data from lowercase text
to uppercase text.
The ENTRY_POINT and MODULE_NAME parameters specify the external routine that
InterBase calls when the filter is invoked. The MODULE_NAME parameter specifies filter.dll,
the dynamic link library containing the filter’s executable code. The ENTRY_POINT
parameter specifies the entry point into the DLL. The example shows only a simple file
name. It is good practice to specify a fully-qualified path name, since users of your
application need to load the file.
Application Blob
Filter:
abcdef SAMPLE ABCDEF
Similarly, when reading data, the SAMPLE filter can easily read Blob data of subtype -2,
and translate it to data of subtype -1.
204 INTERBASE 6
WRITING AN EXTERNAL BLOB FILTER
Blob Application
Filter:
ABCDEF SAMPLE abcdef
When InterBase processes this declaration, it searches a list of filters defined in the
current database for a filter with matching FROM and TO subtypes. If such a filter exists,
InterBase invokes it during Blob operations that use the cursor, BCINS1. If InterBase
cannot locate a filter with matching FROM and TO subtypes, it returns an error to the
application.
Filter types
Filters can be divided into two types: filters that convert data one segment at a time, and
filters that convert data many segments at a time.
The first type of filter reads a segment of data, converts it, and supplies it to the
application a segment at a time.
The second type of filter might read all the data and do all the conversion when the Blob
read cursor is first opened, and then simulate supplying data a segment at a time to the
application.
If timing is an issue for your application, you should carefully consider these two types
of filters and which might better serve your purpose.
206 INTERBASE 6
WRITING AN EXTERNAL BLOB FILTER
APPLICATION
INTERBASE
FILTER
Declare the name of the filter function and the name of the filter executable with the
ENTRY_POINT and MODULE_NAME parameters of the DECLARE FILTER statement.
A filter function must have the following declaration calling sequence:
filter_function_name(short action, isc_blob_ctl control);
The parameter, action, is one of eight possible action macro definitions and the
parameter, control, is an instance of the isc_blob_ctl Blob control structure, defined in
the InterBase header file ibase.h. These parameters are discussed later in this chapter.
The following listing of a skeleton filter declares the filter function, jpeg_filter:
#include <ibase.h>
#define SUCCESS 0
#define FAILURE 1
switch (action)
{
case isc_blob_filter_open:
. . .
break;
case isc_blob_filter_get_segment:
. . .
break;
case isc_blob_filter_create:
. . .
break;
case isc_blob_filter_put_segment:
. . .
break;
case isc_blob_filter_close:
. . .
break;
case isc_blob_filter_alloc:
. . .
break;
case isc_blob_filter_free:
. . .
break;
case isc_blob_filter_seek:
. . .
break;
default:
status = isc_uns_ext /* unsupported action value */
. . .
break;
}
return status;
}
InterBase passes one of eight possible actions to the filter function, jpeg_filter(), by way
of the action parameter, and also passes an instance of the Blob control structure,
isc_blob_ctl, by way of the parameter control.
The ellipses (…) in the previous listing represent code that performs some operations
based on each action, or event, that is listed in the case statement. Each action is a
particular event invoked by a database operation the application might perform. For
more information, see “Programming filter function actions” on page 211.
The isc_blob_ctl Blob control structure provides the fundamental data exchange between
InterBase and the filter. For more information on the Blob control structure, see
“Defining the Blob control structure” on page 208.
208 INTERBASE 6
WRITING AN EXTERNAL BLOB FILTER
210 INTERBASE 6
WRITING AN EXTERNAL BLOB FILTER
These fields are informational only. InterBase does not use the values of these fields in
internal processing.
The following table describes the Blob access operation that corresponds to each action:
Tip Store resource pointers, such as memory pointers and file handles created by the
isc_blob_filter_open handler, in the ctl_data field of the isc_blob_ctl Blob control
structure. Then, the next time the filter function is called, the resource pointers are still
available.
212 INTERBASE 6
WRITING AN EXTERNAL BLOB FILTER
For more information about InterBase status values, see the Language Reference.
214 INTERBASE 6
CHAPTER
Creating arrays
Arrays are defined with the CREATE DOMAIN or CREATE TABLE statements. Defining an array
column is just like defining any other column, except that you must also specify the array
dimensions.
Array indexes range from –231 to +231–1.
The following statement defines a regular character column and a single-dimension,
character array column containing four elements:
EXEC SQL
CREATE TABLE TABLE1
(
NAME CHAR(10),
CHAR_ARR CHAR(10)[4]
);
Array dimensions are always enclosed in square brackets following a column’s datatype
specification.
For a complete discussion of CREATE TABLE and array syntax, see the Language Reference.
Multi-dimensional arrays
InterBase supports multi-dimensional arrays, arrays with 1 to 16 dimensions. For
example, the following statement defines three integer array columns with two, three,
and six dimensions, respectively:
EXEC SQL
CREATE TABLE TABLE1
(
INT_ARR2 INTEGER[4,5]
INT_ARR3 INTEGER[4,5,6]
INT_ARR6 INTEGER[4,5,6,7,8,9]
);
In this example, INT_ARR2 allocates storage for 4 rows, 5 elements in width, for a total of
20 integer elements, INT_ARR3 allocates 120 elements, and INT_ARR6 allocates 60,480
elements.
216 INTERBASE 6
CREATING ARRAYS
IMPORTANT InterBase stores multi-dimensional arrays in row-major order. Some host languages,
such as FORTRAN, expect arrays to be in column-major order. In these cases, care must
be taken to translate element ordering correctly between InterBase and the host
language.
For example, the following statement creates a table with a single-dimension array
column of four elements where the lower boundary is 0 and the upper boundary is 3:
EXEC SQL
CREATE TABLE TABLE1
(
INT_ARR INTEGER[0:3]
);
EXEC SQL
CREATE TABLE TABLE1
(
INT_ARR INTEGER[0:3, 0:3]
);
Accessing arrays
InterBase can perform operations on an entire array, effectively treating it as a single
element, or it can operate on an array slice, a subset of array elements. An array slice can
consist of a single element, or a set of many contiguous elements.
InterBase supports the following data manipulation operations on arrays:
g Selecting data from an array
g Inserting data into an array
g Updating data in an array slice
g Selecting data from an array slice
g Evaluating an array element in a search condition
A user-defined function (UDF) can only reference a single array element.
The following array operations are not supported:
g Referencing array dimensions dynamically in DSQL
g Inserting data into an array slice
g Setting individual array elements to NULL
g Using the aggregate functions, MIN(), MAX(), SUM(), AVG(), and COUNT() with arrays
g Referencing arrays in the GROUP BY clause of a SELECT
g Creating views that select from array slices
218 INTERBASE 6
ACCESSING ARRAYS
2. Declare a cursor that specifies the array columns to select. For example,
EXEC SQL
DECLARE TC1 CURSOR FOR
SELECT NAME, CHAR_ARR[], INT_ARR[]
FROM TABLE1;
Be sure to include brackets ([]) after the array column name to select the array data.
If the brackets are left out, InterBase reads the array ID for the column, instead of the
array data.
The ability to read the array ID, which is actually a Blob ID, is included only to
support applications that access array data using InterBase API calls.
3. Open the cursor, and fetch data:
EXEC SQL
OPEN TC1;
EXEC SQL
FETCH TC1 INTO :name, :char_arr, :int_arr;
Note It is not necessary to use a cursor to select array data. For example, a singleton
SELECT might be appropriate, too.
When selecting array data, keep in mind that InterBase stores elements in row-major
order. For example, in a 2-dimensional array, with 2 rows and 3 columns, all 3 elements
in row 1 are returned, then all three elements in row two.
IMPORTANT When inserting data into an array column, provide data to fill all array elements, or the
results will be unpredictable.
220 INTERBASE 6
ACCESSING ARRAYS
EXEC SQL
SELECT JOB_TITLE[2:4]
INTO :title
FROM EMPLOYEE
WHERE LAST_NAME = :lname;
For multi-dimensional arrays, the lower and upper values for each dimension must be
specified, separated from one another by commas, using the following syntax:
[lower:upper, lower:upper [, lower:upper ...]]
Because InterBase stores array data in row-major order, the first range of values between
the brackets specifies the subset of rows to retrieve. The second range of values specifies
which elements in each row to retrieve.
To select data from an array slice, perform the following steps:
1. Declare a host-language variable large enough to hold the array slice data
retrieved. For example,
EXEC SQL
BEGIN DECLARE SECTION;
char char_slice[11]; /* 11-byte string for CHAR(10) datatype
*/
long int_slice[2][3];
EXEC SQL
END DECLARE SECTION;
The first variable, char_slice, is intended to store a single element from the CHAR_ARR
column. The second example, int_slice, is intended to store a six-element slice from
the INT_ARR integer column.
2. Declare a cursor that specifies the array slices to read. For example,
EXEC SQL
DECLARE TC2 CURSOR FOR
SELECT CHAR_ARR[1], INT_ARR[1:2,1:3]
FROM TABLE1
EXEC SQL
OPEN TC2;
EXEC SQL
FETCH TC2 INTO :char_slice, :int_slice;
The first variable, char_slice, is intended to hold a single element of the CHAR_ARR
array column defined in the programming example in the previous section. The
second example, int_slice, is intended to hold a six-element slice of the INT_ARR
integer array column.
2. Select the row that contains the array data to modify. For example, the
following cursor declaration selects data from the INT_ARRAY and CHAR_ARRAY
columns:
EXEC SQL
DECLARE TC1 CURSOR FOR
SELECT CHAR_ARRAY[1], INT_ARRAY[1:2,1:3] FROM TABLE1;
EXEC SQL
OPEN TC1;
EXEC SQL
FETCH TC1 INTO :char_slice, :int_slice;
This example fetches the data currently stored in the specified slices of CHAR_ARRAY
and INT_ARRAY, and stores it into the char_slice and int_slice host-language variables,
respectively.
3. Load the host-language variables with new or updated data.
222 INTERBASE 6
ACCESSING ARRAYS
4. Execute an UPDATE statement to insert data into the array slices. For example,
the following statements put data into parts of CHAR_ARRAY and INT_ARRAY,
assuming char_slice and int_slice contain information to insert into the table:
EXEC SQL
UPDATE TABLE1
SET
CHAR_ARR[1] = :char_slice,
INT_ARR[1:2,1:3] = :int_slice
WHERE CURRENT OF TC1;
The following fragment of the output from this example illustrates the contents of the
columns, CHAR_ARR and INT_ARR after this operation.
char_arr values:
[0]:string0 [1]:NewString [2]:string2 [3]:string3
int_arr values:
updated values
[0][0]:0 [0][1]:1 [0][2]:2 [0][3]:3
[1][0]:10 [1][1]:999 [1][2]:999 [1][3]:999
[2][0]:20 [2][1]:999 [2][2]:999 [2][3]:999
[3][0]:30 [3][1]:31 [3][2]:32 [3][3]:33
224 INTERBASE 6
CHAPTER
Working with
Chapter10
10
Stored Procedures
g Improved performance, especially for remote client access. Stored procedures are
executed by the server, not the client.
This chapter describes how to call and execute stored procedures in applications once
they are written. For information on how to create a stored procedure, see the Data
Definition Guide.
226 INTERBASE 6
USING SELECT PROCEDURES
SUSPEND;
END !!
The following statement retrieves PROJ_ID from the above procedure, passing the host
variable, number, as input:
SELECT PROJ_ID FROM GET_EMP_PROJ (:number);
IMPORTANT InterBase does not support creating a view by calling a select procedure.
The following application C code with embedded SQL then uses the PROJECTS cursor to
print project numbers to standard output:
EXEC SQL
OPEN PROJECTS
228 INTERBASE 6
USING EXECUTABLE PROCEDURES
if (SQLCODE == 100)
break;
if (nullind == 0)
printf("\t%s\n", proj_id);
}
Executing a procedure
To execute a procedure in an application, use the following syntax:
EXEC SQL
EXECUTE PROCEDURE name [:param [[INDICATOR]:indicator]]
[, :param [[INDICATOR]:indicator] ...]
[RETURNING_VALUES :param [[INDICATOR]:indicator]
[, :param [[INDICATOR]:indicator]...]];
When an executable procedure uses input parameters, the parameters can be literal
values (such as 7 or “Fred”), or host variables. If a procedure returns output parameters,
host variables must be supplied in the RETURNING_VALUES clause to hold the values
returned.
For example, the following statement demonstrates how the executable procedure,
DEPT_BUDGET, is called with literal parameters:
EXEC SQL
EXECUTE PROCEDURE DEPT_BUDGET 100 RETURNING_VALUES :sumb;
The following statement also calls the same procedure using a host variable instead of a
literal as the input parameter:
EXEC SQL
EXECUTE PROCEDURE DEPT_BUDGET :rdno RETURNING_VALUES :sumb;
4 Indicator variables
Both input parameters and return values can have associated indicator variables for
tracking NULL values. You must use indicator variables to indicate unknown or NULL
values of return parameters. The INDICATOR keyword is optional. An indicator variable
that is less than zero indicates that the parameter is unknown or NULL. An indicator
variable that is 0 indicates that the associated parameter contains a non-NULL value. For
more information about indicator variables, see Chapter 6, “Working with Data.”
3. Use DESCRIBE OUTPUT to set up an output XSQLDA using the following syntax:
EXEC SQL
DESCRIBE OUTPUT sql_statement_name INTO SQL DESCRIPTOR
output_xsqlda;
Setting up an output XSQLDA is only necessary for procedures that return values.
4. Execute the statement using the following syntax:
EXEC SQL
EXECUTE statement USING SQL DESCRIPTOR input_xsqlda
INTO DESCRIPTOR output_xsqlda;
230 INTERBASE 6
USING EXECUTABLE PROCEDURES
EXEC SQL
DESCRIBE INPUT QUERY INTO SQL DESCRIPTOR input_xsqlda;
EXEC SQL
DESCRIBE OUTPUT QUERY INTO SQL DESCRIPTOR output_xsqlda;
EXEC SQL
EXECUTE QUERY USING SQL DESCRIPTOR input_xsqlda INTO SQL DESCRIPTOR
output_xsqlda;
. . .
232 INTERBASE 6
CHAPTER
234 INTERBASE 6
REGISTERING INTEREST IN EVENTS
Note POST_EVENT is a stored procedure and trigger language extension, available only
within stored procedures and triggers.
For a complete discussion of writing a trigger or stored procedure as an event alerter, see
the Data Definition Guide.
After an application registers interest in an event, it is not notified about an event until it
first pauses execution with EVENT WAIT. For more information about waiting for events,
see “Waiting for events with EVENT WAIT” on page 236.
Note As an alternative to registering interest in an event and waiting for the event to
occur, applications can use an InterBase API call to register interest in an event, and
identify an asynchronous trap (AST) function to receive event notification. This method
enables an application to continue other processing instead of waiting for an event to
occur. For more information about programming events with the InterBase API, see the
API Guide.
Note An application can also register interest in multiple events by using a separate
EVENT INIT statement with a unique request handle for a single event or groups of events,
but it can only wait on one request handle at a time.
236 INTERBASE 6
RESPONDING TO EVENTS
request_name must be the name of a request handle declared in a previous EVENT INIT
statement.
The following statements register interest in an event, and wait for event notification:
EXEC SQL
EVENT INIT RESPOND_NEW (’new_order’);
EXEC SQL
EVENT WAIT RESPOND_NEW;
Once EVENT WAIT is executed, application processing stops until the event manager sends
a notification message to the application.
Note An application can contain more than one EVENT WAIT statement, but all processing
stops when the first statement is encountered. Each time processing restarts, it stops
when it encounters the next EVENT WAIT statement.
If one event occurs while an application is processing another, the event manager sends
notification the next time the application returns to a wait state.
Responding to events
When event notification occurs, a suspended application resumes normal processing at
the next statement following EVENT WAIT.
If an application has registered interest in more than one event with a single EVENT INIT
call, then the application must determine which event occurred by examining the event
array, isc_event[]. The event array is automatically created for an application during
preprocessing. Each element in the array corresponds to an event name passed as an
argument to EVENT INIT. The value of each element is the number of times that event
occurred since execution of the last EVENT WAIT statement with the same request handle.
In the following code, an application registers interest in three events, then suspends
operation pending event notification:
EXEC SQL
EVENT INIT RESPOND_MANY (’new_order’, ’change_order’,
’cancel_order’);
EXEC SQL
EVENT WAIT RESPOND_MANY;
When any of the “new_order,” “change_order,” or “cancel_order” events are posted and
their controlling transactions commit, the event manager notifies the application and
processing resumes. The following code illustrates how an application might test which
event occurred:
238 INTERBASE 6
CHAPTER
All SQL applications should include mechanisms for trapping, responding to, and
recovering from run-time errors, the errors that can occur when someone uses an
application. This chapter describes both standard, portable SQL methods for handling
errors, and additional error handling specific to InterBase.
Value Meaning
0 Success
1–99 Warning or informational message
100 End of file (no more data)
<0 Error. Statement failed to complete
TABLE 12.1 Possible SQLCODE values
To trap and respond to run-time errors, SQLCODE should be checked after each SQL
operation. There are three ways to examine SQLCODE and respond to errors:
g Use WHENEVER statements to automate checking SQLCODE and handle errors when they
occur.
g Test SQLCODE directly after individual SQL statements.
g Use a judicious combination of WHENEVER statements and direct testing.
Each method has advantages and disadvantages, described fully in the remainder of this
chapter.
WHENEVER statements
The WHENEVER statement enables all SQL errors to be handled with a minimum of coding.
WHENEVER statements specify error-handling code that a program should execute when
SQLCODE indicates errors, warnings, or end-of-file. The syntax of WHENEVER is:
EXEC SQL
WHENEVER {SQLERROR | SQLWARNING | NOT FOUND}
{GOTO label | CONTINUE};
After WHENEVER appears in a program, all subsequent SQL statements automatically jump
to the specified code location identified by label when the appropriate error or warning
occurs.
240 INTERBASE 6
STANDARD ERROR HANDLING
Because they affect all subsequent statements, WHENEVER statements are usually
embedded near the start of a program. For example, the first statement in the following
C code’s main() function is a WHENEVER that traps SQL errors:
main()
{
EXEC SQL
WHENEVER SQLERROR GOTO ErrorExit;
. . .
Error Exit:
if (SQLCODE)
{
print_error();
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT;
exit(1);
}
}
. . .
print_error()
{
printf("Database error, SQLCODE = %d\n", SQLCODE);
}
. . .
EXEC SQL
WHENEVER SQLWARNING
CONTINUE;
. . .
This code traps SQLCODE warning values, but ignores them. Ordinarily, warnings should
be investigated, not ignored.
IMPORTANT Use WHENEVER SQLERROR CONTINUE at the start of error-handling routines to disable
error handling temporarily. Otherwise, there is a possibility of an infinite loop; should
another error occur in the handler itself, the routine will call itself again.
242 INTERBASE 6
STANDARD ERROR HANDLING
g Does not easily enable a program to resume processing at the point where the error
occurred. For example, a single WHENEVER SQLERROR can trap data entry that violates a
CHECK constraint at several points in a program, but jumps to a single error-handling
routine. It might be helpful to allow the user to reenter data in these cases, but the error
routine cannot determine where to jump to resume program processing.
Error-handling routines can be very sophisticated. For example, in C or C++, a routine
might use a large CASE statement to examine SQLCODE directly and respond differently to
different values. Even so, creating a sophisticated routine that can resume processing at
the point where an error occurred is difficult. To resume processing after error recovery,
consider testing SQLCODE directly after each SQL statement, or consider using a
combination of error-handling methods.
if (SQLCODE)
{
if (SQLCODE == –1)
printf("too many records found\n");
else if (SQLCODE == 100)
printf("no records found\n");
else
{
printf("Database error, SQLCODE = %d\n", SQLCODE);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT;
exit(1);
}
}
printf("found city named %s\n", city);
EXEC SQL
COMMIT;
EXEC SQL
DISCONNECT;
The disadvantage to checking SQLCODE directly is that it requires many lines of extra code
just to see if an error occurred. On the other hand, it enables errors to be handled with
function calls, as the following C code illustrates:
EXEC SQL
SELECT CITY INTO :city FROM STATES
WHERE STATE = :stat:statind;
switch (SQLCODE)
{
case 0:
break; /* NO ERROR */
case –1
ErrorTooMany();
break;
case 100:
ErrorNotFound();
break;
default:
ErrorExit(); /* Handle all other errors */
break;
}
. . .
Using function calls for error handling enables programs to resume execution if errors
can be corrected.
244 INTERBASE 6
STANDARD ERROR HANDLING
IMPORTANT Use WHENEVER SQLERROR CONTINUE at the start of error-handling routines to disable
error-handling temporarily. Otherwise, there is a possibility of an infinite loop; should
another error occur in the handler itself, the routine will call itself again.
PORTABILITY
For portability among different SQL implementations, SQL programs should limit error
handling to WHENEVER statements or direct examination of SQLCODE values.
InterBase internal error recognition occurs at a finer level of granularity than SQLCODE
representation permits. A single SQLCODE value can represent many different internal
InterBase errors. Where portability is not an issue, it may be desirable to perform
additional InterBase error handling. The remainder of this chapter explains how to use
these additional features.
246 INTERBASE 6
ADDITIONAL INTERBASE ERROR HANDLING
{
isc_print_sqlerror(SQLCODE, isc_status);
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT ALL;
exit(1);
}
. . .
IMPORTANT Some windowing systems do not encourage or permit direct screen writes. Do not use
isc_print_sqlerror() when developing applications for these environments. Instead, use
isc_sql_interprete() and isc_interprete() to capture messages to a buffer for display.
248 INTERBASE 6
ADDITIONAL INTERBASE ERROR HANDLING
IMPORTANT isc_interprete() should not be used unless SQLCODE is less than –1 because the contents
of isc_status may not contain reliable error information in these cases.
Given both the location of a storage buffer previously allocated by the program, and a
pointer to the start of the status array, isc_interprete() builds an error message string from
the information in the status array, and puts the formatted string in the buffer where it
can be manipulated. It also advances the status array pointer to the start of the next
cluster of available error information.
isc_interprete() retrieves and formats a single error message each time it is called. When
an error occurs in an InterBase program, however, the status array may contain more
than one error message. To retrieve all relevant error messages, error-handling routines
should repeatedly call isc_interprete() until it returns no more messages.
Because isc_interprete() modifies the pointer to the status array that it receives, do not
pass isc_status directly to it. Instead, declare a pointer to isc_status, then pass the pointer
to isc_interprete().
The following C code fragment illustrates how InterBase error messages can be captured
to a log file, and demonstrates the proper declaration of a string buffer and pointer to
isc_status. It assumes the log file is properly declared and opened before control is passed
to the error-handling routine. It also demonstrates how to set the pointer to the start of
the status array in the error-handling routine before isc_interprete() is first called.
. . .
#include "ibase.h";
. . .
main()
{
char msg[512];
ISC_STATUS *vector;
FILE *efile; /* code fragment assumes pointer to an open file */
. . .
if (SQLCODE < –1)
ErrorExit();
}
. . .
ErrorExit()
{
vector = isc_status; /* (re)set to start of status vector */
isc_interprete(msg, &vector); /* retrieve first mesage */
fprintf(efile, "%s\n", msg); /* write buffer to log file */
msg[0] = '-'; /* append leading hyphen to secondary messages */
while (isc_interprete(msg + 1, &vector)) /* more?*/
fprintf(efile, "%s\n", msg); /* if so, write it to log */
fclose(efile); /* close log prior to quitting program */
EXEC SQL
ROLLBACK;
EXEC SQL
DISCONNECT ALL;
exit(1); /* quit program with an 'abnormal termination' code */
}
. . .
250 INTERBASE 6
ADDITIONAL INTERBASE ERROR HANDLING
Tip InterBase error codes are mapped to mnemonic definitions (for example, isc_arg_gds)
that can be used in code to make it easier to read, understand, and maintain. Definitions
for all InterBase error codes can be found in the ibase.h file.
The following C code fragment illustrates an error-handling routine that:
g Displays error messages with isc_print_sqlerror().
g Illustrates how to parse for and handle six specific InterBase errors which might be
corrected upon roll back, data entry, and retry.
g Uses mnemonic definitions for InterBase error numbers.
. . .
int c, jval, retry_flag = 0;
jmp_buf jumper;
. . .
main()
{
. . .
jval = setjmp(jumper);
if (retry_flag)
ROLLBACK;
. . .
}
int ErrorHandler(void)
{
retry_flag = 0; /* reset to 0, no retry */
isc_print_sqlerror(SQLCODE, isc_status); /* display errors */
if (SQLCODE < –1)
{
if (isc_status[0] == isc_arg_gds)
{
switch (isc_status[1])
{
case isc_convert_error:
case isc_deadlock:
case isc_integ_fail:
case isc_lock_conflict:
case isc_no_dup:
case isc_not_valid:
printf("\n Do you want to try again? (Y/N)");
c = getchar();
if (c == 'Y' || c == 'y')
{
retry_flag = 1; /* set flag to retry */
longjmp(jumper, 1);
}
break;
case isc_end_arg: /* there really isn’t an error */
retry_flag = 1; /* set flag to retry */
longjump(jumper, 1);
break;
default: /* we can’t handle everything, so abort */
break;
}
}
}
EXEC SQL
252 INTERBASE 6
ADDITIONAL INTERBASE ERROR HANDLING
ROLLBACK;
EXEC SQL
DISCONNECT ALL;
exit(1);
}
254 INTERBASE 6
CHAPTER
DSQL limitations
Although DSQL offers many advantages, it also has the following limitations:
g Access to one database at a time.
g Dynamic transaction processing is not permitted; all named transactions must be
declared at compile time.
g Dynamic access to Blob and array data is not supported; Blob and array data can be
accessed, but only through standard, statically processed SQL statements, or through
low-level API calls.
g Database creation is restricted to CREATE DATABASE statements executed within the context
of EXECUTE IMMEDIATE.
For more information about handling transactions in DSQL applications, see “Handling
transactions” on page 257. For more information about working with Blob data in
DSQL, see “Processing Blob data” on page 259. For more information about handling
array data in DSQL, see “Processing array data” on page 259. For more information
about dynamic creation of databases, see “Creating a database” on page 258.
Accessing databases
Using standard SQL syntax, a DSQL application can only use one database handle per
source file module, and can, therefore, only be connected to a single database at a time.
Database handles must be declared and initialized when an application is preprocessed
with gpre. For example, the following code creates a single handle, db1, and initializes it
to zero:
#include "ibase.h"
isc_db_handle db1;
. . .
db1 = 0L;
256 INTERBASE 6
DSQL LIMITATIONS
CONNECT db1;
. . .
The database accessed by DSQL statements is always the last database handle mentioned
in a SET DATABASE command. A database handle can be used to connect to different
databases as long as a previously connected database is first disconnected with
DISCONNECT. DISCONNECT automatically sets database handles to NULL. The following
statements disconnect from a database, zero the database handle, and connect to a new
database:
EXEC SQL
DISCONNECT db1;
EXEC SQL
SET DATABASE db1 = ’employee.gdb’;
EXEC SQL
CONNECT db1;
To access more than one database using DSQL, create a separate source file module for
each database, and use low-level API calls to attach to the databases and access data. For
more information about accessing databases with API calls, see the API Guide. For more
information about SQL database statements, see Chapter 3, “Working with Databases.”
Handling transactions
InterBase requires that all transaction names be declared when an application is
preprocessed with gpre. Once fixed at precompile time, transaction handles cannot be
changed at run time, nor can new handles be declared dynamically at run time.
SQL statements such as PREPARE, DESCRIBE, EXECUTE, and EXECUTE IMMEDIATE, can be
coded at precompile time to include an optional TRANSACTION clause specifying which
transaction controls statement execution. The following code declares, initializes, and
uses a transaction handle in a statement that processes a run-time DSQL statement:
#include "ibase.h"
isc_tr_handle t1;
. . .
t1 = 0L;
EXEC SQL
SET TRANSACTION NAME t1;
EXEC SQL
PREPARE TRANSACTION t1 Q FROM :sql_buf;
DSQL statements that are processed with PREPARE, DESCRIBE, EXECUTE, and EXECUTE
IMMEDIATE cannot use a TRANSACTION clause, even if it is permitted in standard,
embedded SQL.
The SET TRANSACTION statement cannot be prepared, but it can be processed with
EXECUTE IMMEDIATE if:
1. Previous transactions are first committed or rolled back.
2. The transaction handle is set to NULL.
For example, the following statements commit the previous default transaction, then start
a new one with EXECUTE IMMEDIATE:
EXEC SQL
COMMIT;
/* set default transaction name to NULL */
gds__trans = NULL;
EXEC SQL
EXECUTE IMMEDIATE ’SET TRANSACTION READ ONLY’;
Creating a database
To create a new database in a DSQL application:
1. Disconnect from any currently attached databases. Disconnecting from a
database automatically sets its database handle to NULL.
2. Build the CREATE DATABASE statement to process.
3. Execute the statement with EXECUTE IMMEDIATE.
For example, the following statements disconnect from any currently connected
databases, and create a new database. Any existing database handles are set to NULL, so
that they can be used to connect to the new database in future DSQL statements.
char *str = "CREATE DATABASE \"new_emp.gdb\"";
. . .
EXEC SQL
DISCONNECT ALL;
EXEC SQL
EXECUTE IMMEDIATE :str;
258 INTERBASE 6
WRITING A DSQL APPLICATION
The following ESQL statements cannot be processed by DSQL: CLOSE, DECLARE, CURSOR,
DESCRIBE, EXECUTE, EXECUTE IMMEDIATE, FETCH, OPEN, PREPARE.
The following ISQL commands cannot be processed by DSQL: BLOBDUMP, EDIT, EXIT, HELP,
INPUT, OUTPUT, QUIT, SET, SET AUTODDL, SET BLOBDISPLAY, SET COUNT, SET ECHO, SET LIST,
SET NAMES, SET PLAN, SET STATS, SET TERM, SET TIME, SHELL, SHOW CHECK, SHOW DATABASE,
SHOW DOMAINS, SHOW EXCEPTIONS, SHOW FILTERS, SHOW FUNCTIONS, SHOW GENERATORS,
SHOW GRANT, SHOW INDEX, SHOW PROCEDURES, SHOW SYSTEM, SHOW TABLES, SHOW
TRIGGERS, SHOW VERSION, SHOW VIEWS.
260 INTERBASE 6
WRITING A DSQL APPLICATION
It is also possible to build strings at run time from a combination of constants. This
method is useful for statements where the variable is not a true constant, or it is a table
or column name, and where the statement is executed only once in the application.
To pass a parameter as a placeholder, the value is passed as a question mark (?)
embedded within the statement string:
char *str = "DELETE FROM CUSTOMER WHERE CUST_NO = ?";
262 INTERBASE 6
UNDERSTANDING THE XSQLDA
short version
char sqldaid[8]
ISC_LONG sqldabc
short sqln
short sqld
XSQLVAR sqlvar[n]
An input XSQLDA consists of a single XSQLDA structure, and one XSQLVAR structure for
each input parameter. An output XSQLDA also consists of one XSQLDA structure and one
XSQLVAR structure for each data item returned by the statement. An XSQLDA and its
associated XSQLVAR structures are allocated as a single block of contiguous memory.
The PREPARE and DESCRIBE statements can be used to determine the proper number of
XSQLVAR structures to allocate, and the XSQLDA_LENGTH macro can be used to allocate the
proper amount of space. For more information about the XSQLDA_LENGTH macro, see
“Using the XSQLDA_LENGTH macro” on page 267.
264 INTERBASE 6
UNDERSTANDING THE XSQLDA
short sqllen Indicates the maximum size, in bytes, of data in the sqldata field. Set by
InterBase during PREPARE or DESCRIBE.
char *sqldata For input descriptors, specifies either the address of a select-list item or a
parameter. Set by the application.
For output descriptors, contains a value for a select-list item. Set by InterBase.
short *sqlind On input, specifies the address of an indicator variable. Set by an application.
On output, specifies the address of column indicator value for a select-list
item following a FETCH. A value of 0 indicates that the column is not NULL; a
value of –1 indicates the column is NULL. Set by InterBase.
short sqlname_length Specifies the length, in bytes, of the data in field, sqlname. Set by InterBase
during DESCRIBE OUTPUT.
char sqlname[32] Contains the name of the column. Not null (\0) terminated. Set by InterBase
during DESCRIBE OUTPUT.
short relname_length Specifies the length, in bytes, of the data in field, relname. Set by InterBase
during DESCRIBE OUTPUT.
TABLE 13.2 XSQLVAR field descriptions
Input descriptors
Input descriptors process SQL statement strings that contain parameters. Before an
application can execute a statement with parameters, it must supply values for them. The
application indicates the number of parameters passed in the XSQLDA sqld field, then
describes each parameter in a separate XSQLVAR structure. For example, the following
statement string contains two parameters, so an application must set sqld to 2, and
describe each parameter:
char *str = "UPDATE DEPARTMENT SET BUDGET = ? WHERE LOCATION = ?";
When the statement is executed, the first XSQLVAR supplies information about the BUDGET
value, and the second XSQLVAR supplies the LOCATION value.
For more information about using input descriptors, see “DSQL programming
methods” on page 273.
Output descriptors
Output descriptors return values from an executed query to an application. The sqld field
of the XSQLDA indicates how many values were returned. Each value is stored in a
separate XSQLVAR structure. The XSQLDA sqlvar field points to the first of these XSQLVAR
structures. The following statement string requires an output descriptor:
char *str = "SELECT * FROM CUSTOMER WHERE CUST_NO > 100";
266 INTERBASE 6
UNDERSTANDING THE XSQLDA
For information about retrieving information from an output descriptor, see “DSQL
programming methods” on page 273.
For more information about using the XSQLDA_LENGTH macro, see “DSQL programming
methods” on page 273.
sqlind
SQL datatype Macro expression C datatype or typedef used?
Array SQL_ARRAY ISC_QUAD No
Array SQL_ARRAY + 1 ISC_QUAD Yes
Blob SQL_BLOB ISC_QUAD No
Blob SQL_BLOB + 1 ISC_QUAD Yes
CHAR SQL_TEXT char[ ] No
CHAR SQL_TEXT + 1 char[ ] Yes
DATE SQL_DATE ISC_DATE No
DATE SQL_DATE + 1 ISC_DATE Yes
DECIMAL SQL_SHORT, SQL_LONG, int, long, double, or ISC_INT64 No
SQL_DOUBLE, or SQL_INT64
268 INTERBASE 6
UNDERSTANDING THE XSQLDA
sqlind
SQL datatype Macro expression C datatype or typedef used?
NUMERIC SQL_SHORT, SQL_LONG, int, long, double, or ISC_INT64 No
SQL_DOUBLE, or SQL_INT64
Note DECIMAL and NUMERIC datatypes are stored internally as SMALLINT, INTEGER, DOUBLE
PRECISION, or 64-bit integer datatypes. To specify the correct macro expression to provide
for a DECIMAL or NUMERIC column, use isql to examine the column definition in the table
to see how InterBase is storing column data, then choose a corresponding macro
expression.
The datatype information for a parameter or select-list item is contained in the sqltype
field of the XSQLVAR structure. The value contained in the sqltype field provides two pieces
of information:
g The datatype of the parameter or select-list item.
g Whether sqlind is used to indicate NULL values. If sqlind is used, its value specifies
whether the parameter or select-list item is NULL (–1), or not NULL (0).
For example, if the sqltype field equals SQL_TEXT, the parameter or select-list item is a
CHAR that does not use sqlind to check for a NULL value (because, in theory, NULL values
are not allowed for it). If sqltype equals SQL_TEXT + 1, then sqlind can be checked to see
if the parameter or select-list item is NULL.
Tip The C language expression, sqltype & 1, provides a useful test of whether a
parameter or select-list item can contain a NULL. The expression evaluates to 0 if the
parameter or select-list item cannot contain a NULL, and 1 if the parameter or select-list
item can contain a NULL. The following code fragment demonstrates how to use the
expression:
if (sqltype & 1 == 0)
{
/* parameter or select-list item that CANNOT contain a NULL */
}
else
{
/* parameter or select-list item CAN contain a NULL */
}
By default, both PREPARE INTO and DESCRIBE return a macro expression of type + 1, so
the sqlind should always be examined for NULL values with these statements.
270 INTERBASE 6
UNDERSTANDING THE XSQLDA
Coercing datatypes
Sometimes when processing DSQL input parameters and select-list items, it is desirable
or necessary to translate one datatype to another. This process is referred to as datatype
coercion. For example, datatype coercion is often used when parameters or select-list
items are of type VARCHAR. The first two bytes of VARCHAR data contain string length
information, while the remainder of the data is the string to process. By coercing the data
from SQL_VARYING to SQL_TEXT, data processing can be simplified.
Coercion can only be from one compatible datatype to another. For example,
SQL_VARYING to SQL_TEXT, or SQL_SHORT to SQL_LONG.
After coercing a character datatype, provide proper storage space for it. The XSQLVAR field,
sqllen, contains information about the size of the uncoerced data. Set the XSQLVAR sqldata
field to the address of the data.
IMPORTANT Do not coerce a larger datatype to a smaller one. Data can be lost in such a translation.
272 INTERBASE 6
DSQL PROGRAMMING METHODS
2. Parse and name the statement string with PREPARE. The name is used in
subsequent calls to EXECUTE:
EXEC SQL
PREPARE SQL_STMT FROM :str;
274 INTERBASE 6
DSQL PROGRAMMING METHODS
Declaring a pointer to the XSQLVAR structure is not necessary, but can simplify
referencing the structure in subsequent statements.
3. Allocate memory for the XSQLDA using the XSQLDA_LENGTH macro. The
following statement allocates storage for in_sqlda:
in_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(10));
In this statement space for 10 XSQLVAR structures is allocated, allowing the XSQLDA
to accommodate up to 10 parameters.
4. Set the version field of the XSQLDA to SQLDA_VERSION1, and set the sqln field
to indicate the number of XSQLVAR structures allocated:
in_sqlda_version = SQLDA_VERSION1;
in_sqlda->sqln = 10;
1. Elicit a statement string from the user or create one that contains the SQL
statement to be processed. For example, the following statement creates an
SQL statement string with placeholder parameters:
char *str = "UPDATE DEPARTMENT SET BUDGET = ?, LOCATION = ?";
This statement string contains two parameters: a value to be assigned to the BUDGET
field and a value to be assigned to the LOCATION field.
2. Parse and name the statement string with PREPARE. The name is used in
subsequent calls to DESCRIBE and EXECUTE:
EXEC SQL
PREPARE SQL_STMT FROM :str;
276 INTERBASE 6
DSQL PROGRAMMING METHODS
- Providing a value for the parameter consistent with its datatype (required).
- Providing a NULL value indicator for the parameter.
The following code example illustrates these steps, looping through each XSQLVAR
structure in the in_sqlda XSQLDA:
for (i=0, var = in_sqlda->sqlvar; i < in_sqlda->sqld; i++, var++)
{
/* Process each XSQLVAR parameter structure here.
The parameter structure is pointed to by var.*/
dtype = (var->sqltype & ~1) /* drop NULL flag for now */
switch(dtype)
{
case SQL_VARYING: /* coerce to SQL_TEXT */
var->sqltype = SQL_TEXT;
/* Allocate local variable storage. */
var->sqldata = (char *)malloc(sizeof(char)*var->sqllen);
. . .
break;
case SQL_TEXT:
var->sqldata = (char *)malloc(sizeof(char)*var->sqllen);
/* Provide a value for the parameter. */
. . .
break;
case SQL_LONG:
var->sqldata = (char *)malloc(sizeof(long));
/* Provide a value for the parameter. */
*(long *)(var->sqldata) = 17;
break;
. . .
} /* End of switch statement. */
if (sqltype & 1)
{
/* Allocate variable to hold NULL status. */
var->sqlind = (short *)malloc(sizeof(short));
}
} /* End of for loop. */
For more information about datatype coercion and NULL indicators, see “Coercing
datatypes” on page 271.
6. Execute the named statement string with EXECUTE. Reference the parameters
in the input XSQLDA with the USING SQL DESCRIPTOR clause. For example, the
following statement executes a statement string named SQL_STMT:
EXEC SQL
EXECUTE SQL_STMT USING SQL DESCRIPTOR in_sqlda;
278 INTERBASE 6
DSQL PROGRAMMING METHODS
Declaring a pointer to the XSQLVAR structure is not necessary, but can simplify
referencing the structure in subsequent statements.
3. Allocate memory for the XSQLDA using the XSQLDA_LENGTH macro. The
following statement allocates storage for out_sqlda:
out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(10));
Space for 10 XSQLVAR structures is allocated in this statement, enabling the XSQLDA to
accommodate up to 10 select-list items.
4. Set the version field of the XSQLDA to SQLDA_VERSION1, and set the sqln field
of the XSQLDA to indicate the number of XSQLVAR structures allocated:
out_sqlda->version = SQLDA_VERSION1;
out_sqlda->sqln = 10;
The statement appears to have only one select-list item (*). The asterisk is a wildcard
symbol that stands for all of the columns in the table, so the actual number of items
returned equals the number of columns in the table.
2. Parse and name the statement string with PREPARE. The name is used in
subsequent calls to statements such as DESCRIBE and EXECUTE:
EXEC SQL
PREPARE SQL_STMT FROM :str;
4. Compare the sqln field of the XSQLDA to the sqld field to determine if the
output descriptor can accommodate the number of select-list items specified
in the statement. If not, free the storage previously allocated to the output
descriptor, reallocate storage to reflect the number of select-list items
specified by sqld, reset sqln and version, then execute DESCRIBE OUTPUT
again:
if (out_sqlda->sqld > out_sqlda->sqln)
{
n = out_sqlda->sqld;
free(out_sqlda);
out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(n));
out_sqlda->sqln = n;
out_sqlda->version = SQLDA_VERSION1;
EXEC SQL
DESCRIBE OUTPUT SQL_STMT INTO SQL DESCRIPTOR out_sqlda;
}
280 INTERBASE 6
DSQL PROGRAMMING METHODS
For more information about datatype coercion and NULL indicators, see “Coercing
datatypes” on page 271.
Opening the cursor causes the statement string to be executed, and an active set of
rows to be retrieved. For more information about cursors and active sets, see Chapter
6, “Working with Data.”
3. Fetch one row at a time and process the select-list items (columns) it
contains. For example, the following loops retrieve one row at a time from
DYN_CURSOR and process each item in the retrieved row with an
application-specific function (here called process_column()):
while (SQLCODE == 0)
{
EXEC SQL
FETCH DYN_CURSOR USING SQL DESCRIPTOR out_sqlda;
if (SQLCODE == 100)
break;
for (i = 0; i < out_sqlda->sqld; i++)
{
process_column(out_sqlda->sqlvar[i]);
}
}
282 INTERBASE 6
DSQL PROGRAMMING METHODS
To reopen a cursor and process select-list items, repeat steps 2–4 of “Executing a
Statement String Within the Context of a Cursor,” in this chapter.
Declaring a pointer to the XSQLVAR structure is not necessary, but can simplify
referencing the structure in subsequent statements.
3. Allocate memory for the XSQLDA using the XSQLDA_LENGTH macro. The
following statement allocates storage for in_slqda:
in_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(10));
In this statement, space for 10 XSQLVAR structures is allocated, allowing the XSQLDA to
accommodate up to 10 input parameters. Once structures are allocated, assign values
to the sqldata field in each XSQLVAR.
4. Set the version field of the XSQLDA to SQLDA_VERSION1, and set the sqln field
of the XSQLDA to indicate the number of XSQLVAR structures allocated:
in_sqlda->version = SQLDA_VERSION1;
in_sqlda->sqln = 10;
Declaring a pointer to the XSQLVAR structure is not necessary, but can simplify
referencing the structure in subsequent statements.
3. Allocate memory for the XSQLDA using the XSQLDA_LENGTH macro. The
following statement allocates storage for out_sqlda:
out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(10));
Space for 10 XSQLVAR structures is allocated in this statement, enabling the XSQLDA to
accommodate up to 10 select-list items.
4. Set the version field of the XSQLDA to SQLDA_VERSION1, and set the sqln field
of the XSQLDA to indicate the number of XSQLVAR structures allocated:
out_sqlda->version = SQLDA_VERSION1;
out_sqlda->sqln = 10;
284 INTERBASE 6
DSQL PROGRAMMING METHODS
1. Elicit a statement string from the user or create one that contains the SQL
statement to be processed. For example, the following statement creates an
SQL statement string with placeholder parameters:
char *str = "SELECT * FROM DEPARTMENT WHERE BUDGET = ?, LOCATION = ?";
This statement string contains two parameters: a value to be assigned to the BUDGET
field and a value to be assigned to the LOCATION field.
2. Prepare and name the statement string with PREPARE. The name is used in
subsequent calls to DESCRIBE and EXECUTE:
EXEC SQL
PREPARE SQL_STMT FROM :str;
4. Compare the sqln field of the XSQLDA to the sqld field to determine if the
input descriptor can accommodate the number of parameters contained in
the statement. If not, free the storage previously allocated to the input
descriptor, reallocate storage to reflect the number of parameters specified by
sqld, reset sqln and version, then execute DESCRIBE INPUT again:
if (in_sqlda->sqld > in_sqlda->sqln)
{
n = in_sqlda->sqld;
free(in_sqlda);
in_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(n));
in_sqlda->sqln = n;
in_sqlda->version = SQLDA_VERSION1;
EXEC SQL
DESCRIBE INPUT SQL_STMT USING SQL DESCRIPTOR in_sqlda;
}
- Providing a value for the parameter consistent with its datatype (required).
- Providing a NULL value indicator for the parameter.
These steps must be followed in the order presented. The following code example
illustrates these steps, looping through each XSQLVAR structure in the in_sqlda
XSQLDA:
for (i=0, var = in_sqlda->sqlvar; i < in_sqlda->sqld; i++, var++)
{
/* Process each XSQLVAR parameter structure here.
The parameter structure is pointed to by var.*/
dtype = (var->sqltype & ~1) /* drop flag bit for now */
switch (dtype)
{
case SQL_VARYING: /* coerce to SQL_TEXT */
var->sqltype = SQL_TEXT;
/* allocate proper storage */
var->sqldata = (char *)malloc(sizeof(char)*var->sqllen);
/* provide a value for the parameter. See case SQL_LONG */
. . .
break;
case SQL_TEXT:
var->sqldata = (char *)malloc(sizeof(char)*var->sqllen);
/* provide a value for the parameter. See case SQL_LONG */
. . .
break;
case SQL_LONG:
var->sqldata = (char *)malloc(sizeof(long));
/* provide a value for the parameter */
*(long *)(var->sqldata) = 17;
break;
. . .
} /* end of switch statement */
if (sqltype & 1)
{
/* allocate variable to hold NULL status */
var->sqlind = (short *)malloc(sizeof(short));
}
} /* end of for loop */
For more information about datatype coercion and NULL indicators, see “Coercing
datatypes” on page 271.
286 INTERBASE 6
DSQL PROGRAMMING METHODS
6. Use DESCRIBE OUTPUT to fill the output XSQLDA with information about the
select-list items returned by the statement:
EXEC SQL
DESCRIBE OUTPUT SQL_STMT INTO SQL DESCRIPTOR out_sqlda;
7. Compare the sqln field of the XSQLDA to the sqld field to determine if the
output descriptor can accommodate the number of select-list items specified
in the statement. If not, free the storage previously allocated to the output
descriptor, reallocate storage to reflect the number of select-list items
specified by sqld, reset sqln and version, and execute DESCRIBE OUTPUT again:
if (out_sqlda->sqld > out_sqlda->sqln)
{
n = out_sqlda->sqld;
free(out_sqlda);
out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(n));
out_sqlda->sqln = n;
out_sqlda->version = SQLDA_VERSION1;
EXEC SQL
DESCRIBE OUTPUT SQL_STMT INTO SQL DESCRIPTOR out_sqlda;
}
8. Set up an XSQLVAR structure for each item returned. Setting up an item
structure involves the following steps:
- Coercing an item’s datatype (optional).
- Allocating local storage for the data pointed to by the sqldata field of the XSQLVAR.
This step is only required if space for local variables is not allocated until run time.
The following example illustrates dynamic allocation of local variable storage space.
- Providing a NULL value indicator for the parameter (optional).
The following code example illustrates these steps, looping through each XSQLVAR
structure in the out_sqlda XSQLDA:
for (i=0, var = out_sqlda->sqlvar; i < out_sqlda->sqld; i++, var++)
{
dtype = (var->sqltype & ~1) /* drop flag bit for now */
switch (dtype)
{
case SQL_VARYING:
var->sqltype = SQL_TEXT;
break;
case SQL_TEXT:
var->sqldata = (char *)malloc(sizeof(char)*var->sqllen);
break;
case SQL_LONG:
var->sqldata = (char *)malloc(sizeof(long));
break;
/* process remaining types */
} /* end of switch statements */
if (sqltype & 1)
{
/* allocate variable to hold NULL status */
var->sqlind = (short *)malloc(sizeof(short));
}
} /* end of for loop */
For more information about datatype coercion and NULL indicators, see “Coercing
datatypes” on page 271.
Opening the cursor causes the statement string to be executed, and an active set of
rows to be retrieved. For more information about cursors and active sets, see Chapter
6, “Working with Data.”
288 INTERBASE 6
DSQL PROGRAMMING METHODS
3. Fetch one row at a time and process the select-list items (columns) it
contains. For example, the following loops retrieve one row at a time from
DYN_CURSOR and process each item in the retrieved row with an
application-specific function (here called process_column()):
while (SQLCODE == 0)
{
EXEC SQL
FETCH DYN_CURSOR USING SQL DESCRIPTOR out_sqlda;
if (SQLCODE == 100)
break;
for (i = 0; i < out_sqlda->sqld; i++)
{
process_column(out_sqlda->sqlvar[i]);
}
}
290 INTERBASE 6
CHAPTER
Preprocessing, Compiling,
Chapter14
14
and Linking
This chapter describes how to preprocess a program by using gpre, and how to compile
and link it for execution.
Preprocessing
After coding an SQL or dynamic SQL (DSQL) program, the program must be
preprocessed with gpre before it can be compiled. gpre translates SQL and DSQL
commands into statements the host-language compiler accepts by generating InterBase
library function calls. gpre translates SQL and DSQL database variables into ones the
host-language compiler accepts and declares these variables in host-language format.
gpre also declares certain variables and data structures required by SQL, such as the
SQLCODE variable and the extended SQL descriptor area (XSQLDA) used by DSQL.
Using gpre
The syntax for gpre is:
gpre [-language] [-options] infile [outfile]
4 Language switches
The language switch specifies the language of the source program. C and C++ are
languages available on all platforms. The switches are shown in the following table:
Switch Language
-c C
-cxx C++
TABLE 14.1 gpre language switches available on all platforms
Switch Language
-al[sys] Ada (Alsys)
-a[da] Ada (VERDIX, VMS, Telesoft)
-ansi ANSI-85 COBOL
-co[bol] COBOL
-f[ortran] FORTRAN
-pa[scal] Pascal
TABLE 14.2 Additional gpre language switches
292 INTERBASE 6
PREPROCESSING
4 Option switches
The option switches specify preprocessing options. The following table describes the
available switches:
Switch Description
-charset name Determines the active character set at compile time, where name is the
character set name.
-d[atabase] filename Declares a database for programs. filename is the file name of the database
to access. Use this option if a program contains SQL statements and does
not attach to the database itself. Do not use this option if the program
includes a database declaration.
-d_float VAX/VMS only. Specifies that double-precision data will be passed from the
application in D_FLOAT format and stored in the database in G_FLOAT
format. Data comparisons within the database will be performed in
G_FLOAT format. Data returned to the application from the database will be
in D_FLOAT format.
-e[ither_case] Enables gpre to recognize both uppercase and lowercase. Use the
-either_case switch whenever SQL keywords appear in code in lowercase
letters. If case is mixed, and this switch is not used, gpre cannot process the
input file. This switch is not
necessary with languages other than C, since they are case-insensitive.
-m[anual] Suppresses the automatic generation of transactions. Use the
-m switch for SQL programs that perform their own transaction handling,
and for all DSQL programs that must, by definition, explicitly control their
own transactions.
-n[o_lines] Suppresses line numbers for C programs.
-o[utput] Directs gpre’s output to standard output, rather than to a file.
-password password Specifies password, the database password, if the program connects to a
database that requires one.
TABLE 14.3 gpre option switches
Switch Description
-r[aw] Prints BLR as raw numbers, rather than as their mnemonic equivalents. This
option cam be useful for making the gpre output file smaller; however, it
will be unreadable.
-sqldialect Sets the SQL dialect. Valid values are 1, 2, and 3.
-user username Specifies username, the database user name, if the program connects to a
database that requires one.
-x handle Gives the database handle identified with the -database option an external
declaration. This option directs the program to pick up a global declaration
from another linked module. Use only if the -d switch is also used.
-z Prints the version number of gpre and the version number of all declared
databases. These databases can be declared either in the program or with
the -database switch.
TABLE 14.3 gpre option switches (continued)
For sites with the appropriate license and are using a language other than C, additional
gpre options can be specified, as described in the following table:
Switch Description
-h[andles] pkg Specifies, pkg, an Ada handles package.
TABLE 14.4 Language-specific gpre option switches
4 Examples
The following command preprocesses a C program in a file named appl1.e. The output
file will be appl1.c. Since no database is specified, the source code must connect to the
database.
gpre -c appl1
The following command is the same as the previous, except that it does not assume the
source code opens a database, instead, explicitly declaring the database, mydb.gdb:
gpre -c appl1 -d mydb.gdb
294 INTERBASE 6
PREPROCESSING
filename is the file specified in the gpre command. extension is the language-specific
file extension for the specified program.
For example, suppose the following command is issued:
gpre -c census
gpre looks for a file called census.e. If gpre finds this file, it processes it as a C program and
generates an output file called census.c. If gpre does not find this file, it returns the
following error:
gpre: can’t open census.e
296 INTERBASE 6
COMPILING AND LINKING
Linking
On Unix platforms, programs can be linked to the following libraries:
g A library that uses pipes, obtained with the -lgds option. This library yields faster links and
smaller images. It also lets your application work with new versions of InterBase
automatically when they are installed.
g A library that does not use pipes, obtained with the -lgds_b option. This library has faster
execution, but binds an application to a specific version of InterBase. When installing a
new version of InterBase, programs must be relinked to use the new features or databases
created with that version.
Under SunOS-4, programs can be linked to a shareable library by using the
-lgdslib option. This creates a dynamic link at run time and yields smaller images with the
execution speed of the full library. This option also provides the ability to upgrade
InterBase versions automatically.
For specific information about linking options for InterBase on a particular platform,
consult the online readme in the interbase directory.
298 INTERBASE 6
APPENDIX
InterBase Document
AppendixA
A
Conventions
300 INTERBASE 6
PRINTING CONVENTIONS
Printing conventions
The InterBase documentation set uses various typographic conventions to identify objects
and syntactic elements.
The following table lists typographic conventions used in text, and provides examples of
their use:
Convention Purpose Example
UPPERCASE SQL keywords, SQL functions, and names of • the SELECT statement retrieves data from the CITY column
all database objects such as tables, columns, in the CITIES table
indexes, and stored procedures • can be used in CHAR, VARCHAR, and BLOB text columns
• the CAST() function
italic New terms, emphasized words, all elements • isc_decode_date()
from host languages, and all user-supplied • the host variable, segment_length
items • contains six variables, or data members
bold File names, menu picks, and all commands • gbak, isql, gsec. gfix
that are entered at a system prompt, • specify the gpre -sqlda old switch
including their switches, arguments, and • a script, ib_udf.sql, in the examples subdirectory
parameters
• the employee.gdb database; the employee database
• the Session | Advanced Settings command
TABLE A.2 Text conventions
Syntax conventions
The following table lists the conventions used in syntax statements and sample code, and
provides examples of their use:
Convention Purpose Example
UPPERCASE Keywords that must be typed exactly as •SET TERM !!;
they appear when used •ADD [CONSTRAINT] CHECK
italic User-supplied parameters that cannot be •CREATE TRIGGER name FOR table;
broken into smaller units •ALTER EXCEPTION name 'message'
302 INTERBASE 6
Index
i
selecting data 218–221 brackets ([ ]), arrays 216, 219–220
storing data 215 buffers
subscripts 217, 224 database cache 47–48
UDFs and 218 byte-matching rules 119
updating 222
views and 218
C
ASC keyword 138
ascending sort order 97, 138 C language
asterisk (*), in code 128 character variables 24
attaching to databases 27, 41 host terminator 28
multiple 38, 43–46 host-language variables 23–25
averages 129 cache buffers 47–48
CACHE keyword 47
calculations 113, 129
B case-insensitive comparisons 116
BASED ON 24 case-sensitive comparisons 117, 119
arrays and 219 CAST() 125, 186
basic_io.a 297 CHAR datatype
basic_io.ada 297 converting to DATE 186
BEGIN DECLARE SECTION 23 description 108
BETWEEN operator 115 CHAR VARYING keyword 109
NOT operator and 115 CHARACTER keyword 108
binary large objects See Blob character sets
Blob API functions 202 converting 119
Blob data 196–213 default 90
deleting 201–202 NONE 90
filtering 203–213 specifying 40, 90
inserting 199–200 character strings
selecting 196–199 comparing 116, 117, 119
storing 192, 194 literal file names 42–44
updating 200–201 CHARACTER VARYING keyword 109
Blob filter function 206 closing
action macro definitions 211–212 databases 30, 38, 49–51
return values 213 multiple 38
Blob filters 203–213 transactions 28–29
external 203 coercing datatypes 271–272
declaring 204 COLLATE clause 136
writing 205 collation orders
invoking 205 GROUP BY clause 140
text 203 ORDER BY clause 139
types 206 WHERE clause 137
Blob segments 194–196 column names
Blob subtypes 193 qualifying 130
Boolean expressions 135 views 94
evaluating 113 column-major order 217
Borland C/C++ See C language columns
ii INTERBASE 6
adding 101 specifying character sets 90
altering 103 CREATE DOMAIN 90–91
computed 93, 102 arrays 216
creating 91 CREATE GENERATOR 98
defining CREATE INDEX 96–97
views 94 DESCENDING option 97
dropping 102 UNIQUE option 97
selecting 128–130 CREATE PROCEDURE 226
eliminating duplicates 128 CREATE TABLE 91–94
sorting by 138 arrays 216
using domainst 90 multiple tables 92
values, returning 129 CREATE VIEW 94–96
COMMIT 29, 50, 54, 74–78 WITH CHECK OPTION 96
multiple databases 38 creating
comparison operators 114–122 arrays 216–217
NULL values and 114, 121 columns 91
precedence 123 computed columns 93, 102
subqueries 115, 117–122 integrity constraints 91
COMPILETIME keyword 38 metadata 88–98
compiling cursors 144
programs 297–298 arrays 219, 222
computed columns multiple transaction programs 80
creating 93, 102 select procedures 228
defined 93
concatenation operator (||) 112
D
CONNECT 27, 35, 41–48
ALL option 48 data 107
CACHE option 47 accessing 25, 45, 48
error handling 46 DSQL applications 25, 33
multiple databases 43–46 host-language variables and 23
omitting 27 changes
SET DATABASE and 42 committing See COMMIT
constraints 91, 99, 100, 101, 102 rolling back See ROLLBACK
See also specific constraints defining 87
optional 92 protecting See security
CONTAINING operator 116 retrieving
NOT operator and 116 optimizing 142, 225
conversion functions 125–126, 186 selecting 96, 110, 126
converting multiple tables 130, 133
datatypes 125 storing 215
date and time datatypes 187 data structures
dates 183–189 host-language 25
international character sets 119 database cache buffers 47–48
CREATE DATABASE 89–90 database handles 26, 36, 42
in DSQL 258 DSQL applications 30, 32
global 39
iii
multiple databases 37–38, 44 default transactions
naming 36 access mode parameter 56
scope 39 default behavior 56
transactions and 36, 49 DSQL applications 57
database specification parameter 54, 61 isolation level parameter 56
databases lock resolution parameter 56
attaching to 27, 41 rolling back 29
multiple 38, 43–46 starting 55–57
closing 30, 38, 49–51 deleting See dropping
creating 89–90 DESC keyword 138
declaring multiple 25–27, 37–39 DESCENDING keyword 97
DSQL and attaching 256 descending sort order 97, 138
initializing 25–28 detaching from databases 38, 50
naming 41 directories
opening 35, 41, 43 specifying 36
remote 89 dirty reads 64
datatypes 108–109 DISCONNECT 30, 49
coercing 271–272 multiple databases 38, 50
compatible 125 DISTINCT keyword 128
converting 125 division operator (/) 113
DSQL applications 270–273 domains
macro constants 268–270 creating 90–91
DATE datatype DOUBLE PRECISION datatype 108
converting 186, 187 DROP INDEX 99
description 108, 183 DROP TABLE 100
date literals 111, 189 DROP VIEW 99
dates dropping
converting 183–189 columns 102
inserting 185, 185–186 metadata 98–100
selecting 184–185 DSQL
selecting from tables 183 CREATE DATABASE 258
updating 186 limitations 256
DECIMAL datatype 108 macro constants 268–270
declarations, changing scope 39 programming methods 273–289
DECLARE CURSOR 80 requirements 30–32
DECLARE TABLE 93 DSQL applications 21, 255
declaring accessing data 25, 33
Blob filters 204 arrays and 218
host-language variables 22–25 attaching to databases 256
multiple databases 25–27, 37–39 creating databases 258
one database only 27, 35 data definition statements 87
SQLCODE variable 28 database handles 30, 32
transaction names 59 datatypes 270–273
XSQLDAs 31–32 default transactions 57
default character set 90 executing stored procedures 230
iv INTERBASE 6
multiple transactions 83 posting 234
porting 22 responding to 237
preprocessing 34, 55, 291 executable objects 297
programming requirements 30–34 executable procedures 226, 229–231
SQL statements DSQL 230
embedded 33 input parameters 229–230
transaction names 30, 32–34 EXECUTE 30, 33
transactions 32 EXECUTE IMMEDIATE 31, 33, 84
writing 259 EXECUTE PROCEDURE 229
XSQLDAs 262–273 EXISTS operator 115, 121
DSQL limitations 32–34 NOT operator and 121
DSQL statements 255 expression-based columns See computed columns
dynamic link libraries See DLLs expressions 135
dynamic SQL See DSQL evaluating 113
extended SQL descriptior areas See XSQLDAs
EXTERN keyword 40
E
END DECLARE SECTION 23
error codes and messages 28, 251 F
capturing 248–251 file names
displaying 247 specifying 42–44
error status array 247, 251 files
error-handling routines 46, 239, 246 See also specific files
changing 242 source, specifying 295
disabling 246 FLOAT datatype 108
guidelines 246 FROM keyword 132–134
nesting 246 functions
testing SQLCODE directly 243, 244 aggregate 129–130
WHENEVER and 240–243, 244 conversion 125–126, 186
errors 28 error-handling 246
run-time numeric 98
recovering from 239 user-defined See UDFs
trapping 240, 242, 251
unexpected 246
G
user-defined See exceptions
ESCAPE keyword 118 GEN_ID() 98
EVENT INIT 235 generators
multiple events 236 creating 98
EVENT WAIT 236–237 defined 98
events 233–238 global column definitions 90
See also triggers global database handles 39
alerter 234 gpre 34, 83, 291–297
defined 233 command-line options 293–294
manager 233 databases, specifying 38
multiple 236–237 DSQL applications 55
notifying applications 235–236 handling transactions 257
v
language options 292 INDICATOR keyword 230
file names vs. 295–297 indicator variables 230
-m switch 55, 89 NULL values 230
programming requirements 21 initializing
specifying source files 295 databases 25–28
-sqlda old switch 31 transaction names 59
syntax 291 input parameters 227, 229–230
group aggregates 139 See also stored procedures
grouping rows 139 INSERT
restrictions 140 arrays 219
inserting
See also adding
H
Blob data 199–200
hard-coded strings dates 185–186
file names 42–44 INTEGER datatype 108
HAVING keyword 140 integrity constraints 91
header files See ibase.h See also specific type
host languages 28 optional 92
data structures 25 Interactive SQL See isql
host-language variables 42 interbase.a 297
arrays 224 interbase.ada 297
declaring 22–25 international character sets 119
specifying 131 INTO keyword 131, 143
hosts, specifying 36 IS NULL operator 118
NOT operator and 119
I isc_blob_ctl 208
I/O See input, output field descriptions 209
ibase.h 31, 251 isc_blob_default_desc() 202
identifiers 36 isc_blob_gen_bpb() 202
database handles 36 isc_blob_info() 202
databases 41 isc_blob_lookup_desc() 202
views 94 isc_blob_set_desc() 202
IN operator 116 isc_cancel_blob() 202
NOT operator and 117 isc_close_blob() 202
INDEX keyword 143 isc_create_blob2() 202
indexes isc_decode_date() 185
altering 100, 105–106 isc_decode_sql_date() 183
creating 96–97 isc_decode_sql_time() 183
dropping 99 isc_decode_timestamp() 183
preventing duplicate entries 97 isc_encode_date() 186
primary keys 98 isc_encode_sql_date() 183
sort order 97 isc_encode_timestamp() 183
changing 106 isc_get_segment() 202
system-defined 97 isc_interprete() 248, 249–251
unique 97 isc_open_blob2() 202
vi INTERBASE 6
isc_put_segment() 202 maximum values 129
ISC_QUAD structure 184–185 memory
isc_sql_interprete() 248–249 allocating 47
isc_status 247, 251 metadata 87
ISC_TIMESTAMP 184 altering 100–106
isolation level parameter 54, 61, 63 creating 88–98
default transactions 56 dropping 98–100
failing 100
Microsoft C/C++ See C language
J
minimum values 129
JOIN keyword 143 modifying See altering;updating
joins 134 modules
object 297
K multi-column sorts 138
key constraints See FOREIGN KEY constraints; multi-dimensional arrays
PRIMARY KEY constraints creating 216
keys selecting data 221
primary 98 multi-module programs 40
multiple databases
attaching to 38, 43–46
L closing 38
language options (gpre) 292 database handles 37–38, 44
file names vs. 295–297 declaring 25–27, 37–39
libraries detaching 38, 50
dynamic link See DLLs opening 43
Unix platforms 298 transactions 49
LIKE operator 117 multiple tables
NOT operator and 118 creating 92
limbo transactions 28 selecting data 130, 133
linking multiple transactions 130
programs 297–298 DSQL applications 83
literal strings, file names 42–44 running 79–85
literal symbols 118 multiplication operator (*) 113
lock resolution parameter 54, 61, 69 multi-row selects 132, 144–152
default transactions 56
logical operators 113–114
precedence 114, 124 N
loops See repetitive statements named transactions 54, 72
lost updates 64 starting 57–58
names
column 94, 130
M qualifying 36, 37, 49
-m switch 55 in SELECT statements 130
macro constants 268–270 specifying at run time 42
mathematical operators 113 naming
precedence 113, 123 database handles 36
vii
databases 41 data retrieval 142, 225
transactions 58–60 OR operator 113, 114
views 94 ORDER keyword 143
NATURAL keyword 143 order of evaluation (operators) 122–124
NO RECORD_VERSION 61 changing 124
NO WAIT 61, 69 output parameters
NONE character set option 90 See also stored procedures
non-reproducible reads 64
NOT operator 113
P
BETWEEN operator and 115
CONTAINING operator and 116 parameters
EXISTS operator and 121 access mode 56, 62
IN operator and 117 database specification 54, 61, 72
IS NULL operator and 119 isolation level 54, 56, 61, 63
LIKE operator and 118 lock resolution 54, 56, 61, 69
SINGULAR operator and 122 table reservation 54, 61, 71
STARTING WITH operator and 119 unknown 230
NOW 111 phantom rows 64
NOW date literal 189 PLAN keyword 142
NULL values porting
aggregate functions 130 applications 22, 246
arrays and 218 arrays 217
comparisons 114, 121 POST_EVENT 234
indicator variables 230 precedence of operators 122–124
numbers changing 124
generating 98 PREPARE 30, 83
NUMERIC datatype 109 preprocessor See gpre
converting to DATE 186 PRIMARY KEY constraints 97
numeric function 98 primary keys 98
numeric values See values privileges See security
procedures See stored procedures
programming
O DSQL applications 30–34
object modules 297 gpre 21
opening programs
databases 35, 41, 43 compiling and linking 297–298
multiple 43 projection (defined) 126
operators PROTECTED READ 71
arithmetic 113 PROTECTED WRITE 71
comparison 114–122 protecting data See security
concatenation 112
logical 113–114
Q
precedence 122–124
changing 124 qualify (defined) 36, 49
string 112 queries 96, 126
optimizing See also SQL
viii INTERBASE 6
eliminating duplicate columns 128 changing 39
grouping rows 139 database handles 39
multi-column sorts 138 WHENEVER 242
restricting row selection 134, 140 search conditions (queries) 110–122, 135–137
search conditions 110–122, 135–137 arrays and 223–224
arrays and 223–224 combining simple 113
combining simple 113 reversing 113
reversing 113 SELECT 110–122, 126–144, 227
selecting multiple rows 132, 144–152 arrays 218–221
selecting single rows 143 CREATE VIEW and 94, 95
sorting rows 138 DISTINCT option 128
specific tables 132–134 FROM clause 132–134
with joins 134, 143 GROUP BY clause 139–140
query optimizer 142 collation order 140
HAVING clause 140
INTO option 131, 143
R
ORDER BY clause 138
READ COMMITTED 61, 63, 65 collation order 139
read-only views 95 PLAN clause 142
RECORD_VERSION 61 TRANSACTION option 130
remote databases 89 WHERE clause 110–125, 134–137, 144
RESERVING clause 61, 70 ALL operator 120
table reservation options 71 ANY operator 120
result tables 144 BETWEEN operator 115
See also joins CAST option 125, 186
ROLLBACK 29, 50, 54, 74, 78–79 collation order 137
multiple databases 38 CONTAINING operator 116
rollbacks 29 EXISTS operator 121
routines 226 IN operator 117
See also error-handling routines IS NULL operator 119
row-major order 217 LIKE operator 118
rows SINGULAR operator 121
counting 129 SOME operator 120
grouping 139 STARTING WITH operator 119
restrictions 140 select procedures 226, 227–229
selecting 134 calling 228
multiple 132, 144–152 cursors 228
single 143 input parameters 227
sorting 138 selecting 132
run-time errors tables vs. 227
recovering from 239 views vs. 227
RUNTIME keyword 39 SELECT statements
singleton SELECTs 126, 131, 143
S selecting
scope Blob data 196–199
ix
columns 128–130 file names 42–44
data 96, 110, 126 host-language variables 131
See also SELECT hosts 36
dates 184–185 SQL statements
multiple rows 132, 144–152 DSQL applications 33
single rows 143 strings 261
views 132 sql_encode_sql_time() 183
SET DATABASE 26, 35 SQLCODE variable
COMPILETIME option 38 declaring 28
CONNECT and 42 examining 240
DSQL applications 32 return values 240, 247, 251
EXTERN option 40 displaying 247
multiple databases and 37, 44 testing 243, 244
omitting 27, 44 SQLDAs 31
RUNTIME option 39 porting applications and 22
STATIC option 40 starting default transactions 55–57
SET NAMES 35 STARTING WITH operator 119
SET TRANSACTION 54, 56, 60–72 NOT operator and 119
access mode parameter 54 statements
parameters 61 See also DSQL statements; SQL statements
syntax 62 data definition 87
SHARED READ 71 data structures and 25
SHARED WRITE 71 embedded 28, 107
singleton SELECTs 126, 131 error-handling 246
defined 143 transaction management 53, 54
SINGULAR operator 115, 121 STATIC keyword 40
NOT operator and 122 status array See error status array
SMALLINT datatype 109 sticky sort order 138
SNAPSHOT 61, 63, 65 stored procedures 225–231, 233
SNAPSHOT TABLE STABILITY 61, 63, 68 defined 225
SOME operator 115, 120 return values 226, 230
SORT MERGE keywords 143 values 226, 230
sort order XSQLDAs and 230
ascending 97, 138 string operator (||) 112
descending 97, 138 subqueries
indexes 97, 106 comparison operators 115, 117–122
queries 138 defined 161
sticky 138 subscripts (arrays) 217, 224
sorting subtraction operator (-) 113
multiple columns 138 SunOS-4 platforms 298
rows 138 system tables 89
source files 295 system-defined indexes 97
specifying
character sets 40, 90
T
directories 36
table names
x INTERBASE 6
aliases 134 named 54, 72
duplicating 92 starting 57–58
identical 36, 37, 49 naming 58–60
table reservation parameter 54, 61 rolling back 29
tables running multiple 79–85, 130
altering 101–104 unnamed 29
appending with UNION 141 trapping
creating 91–94 errors 240, 242, 251
multiple 92 triggers 233
declaring 93
dropping 100
U
qualifying 36, 37, 49
querying specific 132–134 UDFs
select procedures vs. 227 arrays and 218
TIME datatype unexpected errors 246
converting 186, 187 UNION
time structures 184 appending tables 141
time.h 184 in SELECT statements 127
times unique indexes 97
inserting 185 UNIQUE keyword 97
selecting from tables 183 unique values 98
updating 186 Unix platforms 298
TIMESTAMP datatype unknown values, testing for 118
converting 186, 187 unrecoverable errors 246
TODAY 111 updatable views 95
TODAY date literal 189 UPDATE
TOMORROW 111 arrays 223
totals, calculating 129 dates and times 186
TRANSACTION keyword 130 update side effects 64
transaction management statements 53, 54 updating
transaction names 57, 257 See also altering
declaring 59 updating Blob data 200–201
DSQL applications 30, 32–34 user-defined functions See UDFs
initializing 59 USING clause 61, 72
multi-table SELECTs 130
transactions 226 V
accessing data 48 values
closing 28–29 See also NULL values
committing 29 comparing 114
database handles and 36, 49 manipulating 113
default 55–57 matching 116, 120
rolling back 29 maximum 129
DSQL applications 32 minimum 129
ending 74 selecting 129
multiple databases 49 stored procedures 226, 230
xi
unique 98 embedding 242
unknown, testing for 118 limitations 242
VARCHAR datatype 109 scope 242
variables WHERE clause See SELECT
host-language 42 WHERE keyword 134
arrays 224 wildcards in string comparisons 117
declaring 22–25 writing external Blob filters 205
specifying 131
indicator 230
X
views 94
altering 100, 105 XSQLDA_LENGTH macro 267
arrays and 218 XSQLDAs 262–273
creating 94–96 declaring 31–32
defining columns 94 fields 264
dropping 99 input descriptors 266
naming 94 output descriptors 266
read-only 95 porting applications and 22
select procedures vs. 227 stored procedures and 230
selecting 132 structures 31
updatable 95 XSQLVAR structure 262
virtual tables 94 fields 265
W Y
WAIT 61, 69 YESTERDAY 111
WHENEVER 240–243, 244
xii INTERBASE 6