INFORMIX
Informix Guide to SQL: Syntax
Chapter 1: SQL Statements
Home Contents Index Master Index New Book

SQL Statements

FETCH

Use the FETCH statement to move a cursor to a new row in the active set and to retrieve the row values from memory.

Syntax

(1 of 2)

Element Purpose Restrictions Syntax

cursor id

Identifier for a select or function cursor from which rows are to be retrieved

A DECLARE statement must have previously created the cursor and the OPEN statement must have previously open it.

Identifier, p. 1-966

cursor variable

Host variable that holds the value of cursor id

The host variable must be a character data type. The cursor identified in cursor variable must have been created in an earlier DECLARE statement and opened in an earlier OPEN statement.

Variable name must conform to language-specific rules for variable names.

data structure

Structure that has been declared as a host variable

The individual members of the data structure must be matched appropriately to the type of values that are being fetched. If you use a program array, you must list both the array name and a specific element of the array in data structure.

Data-structure name must conform to language-specific rules for data-structure names.

data variable

Host variable that receives one value from the fetched row

The host variable must have a data type that is appropriate for the value that is fetched into it.

Variable name must conform to language-specific rules for variable names.

descriptor

Quoted string that identifies the system-descriptor area into which you fetch the contents of a row

The system-descriptor area must have been allocated with the ALLOCATE DESCRIPTOR statement.

Quoted String, p. 1-1014

descriptor variable

Host variable name that holds the value of descriptor

The system-descriptor area that is identified in descriptor variable must have been allocated with the ALLOCATE DESCRIPTOR statement.

Variable name must conform to language-specific rules for variable names.

indicator variable

Host variable that receives a return code if null data is placed in the corresponding data variable

This parameter is optional, but use an indicator variable if the possibility exists that the value of data variable is null. If you specify the indicator variable without the INDICATOR keyword, you cannot put a space between data variable and indicator variable. The rules for placing a prefix before indicator variable are language-specific. See your SQL API manual for further information on indicator variables.

Variable cannot be a DATETIME or INTERVAL data type.

Variable name must conform to language-specific rules for variable names.

row position

Integer value or host variable that contains an integer value. The integer value gives the position of the desired row in the active set of rows. See "FETCH with a Scroll Cursor" for a discussion of the RELATIVE and ABSOLUTE keywords and the meaning of row position with each keyword.

A value of 0 for row position is allowed with the RELATIVE keyword. A value of 0 fetches the current row. The value of row position must be 1 or higher with the ABSOLUTE keyword.

If you are using a host variable, variable name must conform to language-specific rules for variable names. If you are using a literal number, see Literal Number, p. 1-1001.

sqlda pointer

Pointer to an sqlda structure that receives the values from the fetched row

You cannot begin an sqlda pointer with a dollar sign ($) or a colon (:).

See the discussion of sqlda structure in the INFORMIX-ESQL/C Programmer's Manual.

Usage

The FETCH statement is one of four statements that are used for queries that return more than one row from the database. The four statements, DECLARE, OPEN, FETCH, and CLOSE, are used in the following sequence:

    1. Declare a select or function cursor to control the active set of rows.

    2. Open the cursor to begin execution of the query.

    3. Fetch from the cursor to retrieve the contents of each row.

    4. Close the cursor to break the association between the cursor and the active set.

You can declare a select or function cursor with either of the following cursor characteristics: a sequential cursor or a scroll cursor. The way the database server creates and stores members of the active set and then fetches rows from the active set differs depending on whether the cursor is a sequential cursor or a scroll cursor. (For more information, see "Cursor Characteristics" in the DECLARE statement)

X/O
In X/Open mode, if a cursor-direction value (such as NEXT or RELATIVE) is specified, a warning message is issued, indicating that the statement does not conform to X/Open standards.

FETCH with a Sequential Cursor

A sequential select or function cursor can fetch only the next row in sequence from the active set. The sole cursor-direction option that is available to a sequential cursor is the default value, NEXT. A sequential cursor can read through a table only once each time it is opened. The following example in INFORMIX-ESQL/C illustrates a FETCH statement with a sequential cursor:

When the program opens a sequential cursor, the database server processes the query to the point of locating or constructing the first row of data. The goal of the database server is to tie up as few resources as possible.

Because the sequential cursor can retrieve only the next row, the database server can frequently create the active set one row at a time. On each FETCH operation, the database server returns the contents of the current row and locates the next row. This one-row-at-a-time strategy is not possible if the database server must create the entire active set to determine which row is the first row (as would be the case if the SELECT statement included an ORDER BY clause).

FETCH with a Scroll Cursor

A scroll select or function cursor can fetch any row in the active set, either by specifying an absolute row position or a relative offset. Use the following cursor-position options to specify a particular row that you want to retrieve.

Keyword Effect

NEXT

Retrieves the next row in the active set.

PREVIOUS

Retrieves the previous row in the active set.

PRIOR

Is synonymous with PREVIOUS; it retrieves the previous row in the active set.

FIRST

Retrieves the first row in the active set.

LAST

Retrieves the last row in the active set.

CURRENT

Retrieves the current row in the active set (the same row as returned by the preceding FETCH statement from the scroll cursor).

RELATIVE

Retrieves the nth row, relative to the current cursor position in the active set, where row position supplies n. A negative value indicates the nth row prior to the current cursor position. If row position is 0, the current row is fetched.

ABSOLUTE

Retrieves the nth row in the active set, where row position supplies n. Absolute row positions are numbered from 1.

The following INFORMIX-ESQL/C examples illustrate a FETCH statement with a scroll cursor:

Row Numbers

The row numbers that are used with the ABSOLUTE keyword are valid only while the cursor is open. Do not confuse them with rowid values. A rowid value is based on the position of a row in its table and remains valid until the table is rebuilt. A row number for a FETCH statement is based on the position of the row in the active set of the cursor; the next time the cursor is opened, different rows might be selected.

How the Database Server Stores Rows

The database server must retain all the rows in the active set for a scroll cursor until the cursor closes, because it cannot be sure which row the program asks for next. When a scroll cursor opens, the database server implements the active set as a temporary table although it might not fill this table immediately.

The first time a row is fetched, the database server copies it into the temporary table as well as returning it to the program. When a row is fetched for the second time, it can be taken from the temporary table. This scheme uses the fewest resources in case the program abandons the query before it fetches all the rows. Rows that are never fetched are usually not created or are saved in a temporary table.

Specifying Where Values Go in Memory

Each value from the select list of the query or the output of a user-defined function must be returned into a memory location. You can specify these destinations in one of the following ways:

INTO Clause of SELECT

When you associate a SELECT statement with the cursor (a select cursor), the SELECT can contain an INTO clause to specify the program variables that are to receive the column values. In this case, the FETCH statement cannot contain an INTO clause. You can use this method only when the SELECT statement is written as part of the declaration of a cursor (see the DECLARE statement on page 1-303). The following example uses the INTO clause of the SELECT statement to specify program variables in INFORMIX-ESQL/C:

Use an indicator variable if the data that is returned from the SELECT statement might be null. See your SQL API manual for more information about indicator variables.

If you prepare a SELECT statement, the SELECT cannot include the INTO clause so you must use the INTO clause of the FETCH statement. For more information, see page 1-418.

INTO Clause of EXECUTE FUNCTION

When you associate an EXECUTE FUNCTION statement with the cursor (a function cursor), the EXECUTE FUNCTION can contain an INTO clause to specify the program variables that are to receive the return values. In this case, the FETCH statement cannot contain an INTO clause. You can use this method only when the EXECUTE FUNCTION statement is written as part of the declaration of a cursor (see the DECLARE statement on page 1-303).

Tip: In earlier versions of Informix products, you could use the EXECUTE PROCEDURE statement to execute a stored procedure that returned values (an SPL function). For backward compatibility, the EXECUTE PROCEDURE statement still supports the INTO clause to receive return values. However, Informix recommends that new SPL functions use EXECUTE FUNCTION and the INTO clause. For more information, see "EXECUTE PROCEDURE".
The following example uses the INTO clause of the EXECUTE FUNCTION statement to specify program variables in INFORMIX-ESQL/C:

Use an indicator variable if the data that is returned from the EXECUTE FUNCTION statement might be null. See INFORMIX-ESQL/C Programmer's Manual for more information about indicator variables.

INTO Clause of FETCH

When the SELECT or EXECUTE FUNCTION statement omits the INTO clause, you must specify the destination of the data whenever a row is fetched. For example, to dynamically execute a SELECT or EXECUTE FUNCTION statement, the SELECT or EXECUTE FUNCTION cannot include its INTO clause in the PREPARE statement. Therefore, the FETCH statement must include an INTO clause to retrieve data into a set of variables. This method lets you store different rows in different memory locations.

In the following INFORMIX-ESQL/C example, a series of complete rows is fetched into a program array. The INTO clause of each FETCH statement specifies an array element as well as the array name.

You can fetch into a program-array element only by using an INTO clause in the FETCH statement. When you are declaring a cursor, do not refer to an array element within the SQL statement.

Using a System-Descriptor Area

If you do not know the number of return values or their data types that a SELECT or EXECUTE FUNCTION statement returns at runtime, you can store output values in a system-descriptor area. A system-descriptor area describes the data type and memory location of one or more return values.

X/O
You can also use an sqlda structure to dynamically supply parameters (
page 1-420). However, a system-descriptor area conforms to the X/Open standards.

Tip: If you are certain of the number and data type of values in the select list, you can use an INTO clause in the FETCH statement. For more information, see page 1-418.
To specify a system-descriptor area as the location of output values, use the USING SQL DESCRIPTOR clause of the FETCH statement. This clause introduces the name of the system-descriptor area into which you fetch the contents of a row or the return values of a user-defined function. You can then use the GET DESCRIPTOR statement to transfer the values that the FETCH statement returns from the system-descriptor area into host variables.

The following example shows the FETCH USING SQL DESCRIPTOR statement:

The COUNT field in the system-descriptor area corresponds to the number of return values of the prepared statement. The value of COUNT must be less than or equal to the value of the occurrences that were specified when the system-descriptor area was allocated with the ALLOCATE DESCRIPTOR statement. You can obtain the value of a field with the GET DESCRIPTOR statement and set the value with the SET DESCRIPTOR statement.

For more information on how to use a system-descriptor area, see the INFORMIX-ESQL/C Programmer's Manual.

Using an sqlda Structure

If you do not know the number of return values or their data types that a SELECT or EXECUTE FUNCTION statement returns at runtime, you can store output values in an sqlda structure. An sqlda structure lists the data type and memory location of one or more return values.

Tip: If you are certain of the number and data type of values in the select list, you can use an INTO clause in the FETCH statement. For more information, see page 1-418.
To specify an sqlda structure as the location of parameters, follow these steps:

    1. Declare an sqlda pointer variable.

    2. Use the DESCRIBE statement to fill in the sqlda structure.

    3. Allocate memory to hold the data values.

    4. Use the USING DESCRIPTOR clause of the FETCH statement to name the sqlda structure as the location into which you fetch the return values.

The following example shows a FETCH USING DESCRIPTOR statement:

The sqld value specifies the number of output values that are described in occurrences of the sqlvar structures of the sqlda structure. This number must correspond to the number of return values from the prepared statement. For further information, refer to the sqlda discussion in the INFORMIX-ESQL/C Programmer's Manual.

Fetching a Row for Update

The FETCH statement does not ordinarily lock a row that is fetched. Thus, another process can modify (update or delete) the fetched row immediately after your program receives it. A fetched row is locked in the following cases:

When you modify a row, the lock is upgraded to a write lock and remains until the cursor is closed or the transaction ends. If you do not modify it, the lock might or might not be released when you fetch another row, depending on the isolation level you have set. The lock on an unchanged row is released as soon as another row is fetched, unless you are using Repeatable Read isolation (see the SET ISOLATION statement on page 1-722).

Important: You can hold locks on additional rows even when Repeatable Read isolation is not in use or is unavailable. Update the row with unchanged data to hold it locked while your program is reading other rows. You must evaluate the effect of this technique on performance in the context of your application, and you must be aware of the increased potential for deadlock.
When you use explicit transactions, be sure that a row is both fetched and modified within a single transaction; that is, both the FETCH statement and the subsequent UPDATE or DELETE statement must fall between a BEGIN WORK statement and the next COMMIT WORK statement.

Fetching From a Collection Cursor

A collection cursor allows you to access the individual elements of an ESQL/C collection variable. To declare a collection cursor, use the DECLARE statement and include the Collection Derived Table segment in the SELECT statement that you associate with the cursor. Once you open the collection cursor with the OPEN statement, the cursor allows you to access the elements of the collection variable.

For more information, see the Collection Derived Table segment on page 1-831. For more information on how to declare a collection cursor for a SELECT statement, see "A Select Cursor for a Collection Variable".

To fetch elements, one at a time, from a collection cursor, use the FETCH statement and the INTO clause. The FETCH statement identifies the collection cursor that is associated with the collection variable. The INTO clause identifies the host variable that holds the element value that is fetched from the collection cursor. The data type of the host variable in the INTO clause must match the element type of the collection.

Suppose you have a table called children with the following structure:

The following ESQL/C code fragment shows how to fetch elements from the child_colors collection variable:

Once you have fetched a collection element, you can modify the element with the UPDATE or DELETE statements. For more information, see the UPDATE and DELETE statements in this manual. You can also insert new elements into the collection variable with an INSERT statement. For more information, see the INSERT statement.

Important: The collection variable stores the elements of the collection. However, it has no intrinsic connection with a database column. Once the collection variable contains the correct elements, you must then save the variable into the collection column with the INSERT or UPDATE statement.

Checking the Result of FETCH

You can use the SQLSTATE variable to check the result of each FETCH statement. The database server sets the SQLSTATE variable after each SQL statement. If a row is returned successfully, the SQLSTATE variable contains the value '00000'. If no row is found, the database server sets the SQLSTATE code to '02000', which indicates no data found, and the current row is unchanged. The following conditions set the SQLSTATE code to '02000', indicating no data found:

The database server copies the SQLSTATE code from the RETURNED_SQLSTATE field of the system-diagnostics area. You can use the GET DIAGNOSTICS statement to examine the RETURNED_SQLSTATE field directly. The system-diagnostics area can also contain additional error information. See the GET DIAGNOSTICS statement in this manual for more information.

Tip: When you encounter an SQLSTATE (sqlca.sqlcode) error, a corresponding SQLCODE error might also exist. The SQLCODE variable contains the
Informix-specific error code. For more information about SQLCODE, see the "Informix Guide to SQL: Tutorial" and the "INFORMIX-ESQL/C Programmer's Manual."

References

See the ALLOCATE DESCRIPTOR, CLOSE, DEALLOCATE DESCRIPTOR, DECLARE, DESCRIBE, GET DESCRIPTOR, OPEN, PREPARE, and SET DESCRIPTOR statements in this manual for further information about using the FETCH statement with dynamic management statements.

In the Informix Guide to SQL: Tutorial, see the discussion of the FETCH statement in Chapter 5.

For further information about error checking, the system-descriptor area and the sqlda structure, see INFORMIX-ESQL/C Programmer's Manual.

FLUSH

Use the FLUSH statement to force rows that a PUT statement buffered to be written to the database.

Syntax

Element Purpose Restrictions Syntax

cursor id

Identifier for a cursor

A DECLARE statement must have previously created the cursor.

Identifier, p. 1-966

cursor variable

Host variable that identifies a cursor

Host variable must be a character data type. A DECLARE statement must have previously created the cursor.

Variable name must conform to language-specific rules for variable names.

Usage

The PUT statement adds a row to a buffer, and the buffer is written to the database when it is full. Use the FLUSH statement to force the insertion when the buffer is not full.

If the program terminates without closing the cursor, the buffer is left unflushed. Rows placed into the buffer since the last flush are lost. Do not expect the end of the program to close the cursor and flush the buffer.

The following example shows a FLUSH statement:

Error Checking FLUSH Statements

The sqlca structure contains information on the success of each FLUSH statement and the number of rows that are inserted successfully. The result of each FLUSH statement is contained in the SQLCODE variable (sqlca.sqlcode) and the sqlerrd[2] field of the sqlca structure.

When you use data buffering with an insert cursor, you do not discover errors until the buffer is flushed. For example, an input value that is incompatible with the data type of the column for which it is intended is discovered only when the buffer is flushed. When an error is discovered, rows in the buffer that are located after the error are not inserted; they are lost from memory.

The SQLCODE field is set either to an error code or to zero if no error occurs. The third element of the sqlerrd array is set to the number of rows that are successfully inserted into the database:

Tip: When you encounter an SQLCODE error, a corresponding SQLSTATE error value might exist. Check the GET DIAGNOSTICS statement for information about getting the SQLSTATE value and using the GET DIAGNOSTICS statement to interpret the SQLSTATE value.

Counting Total and Pending Rows

To count the number of rows actually inserted into the database as well as the number not yet inserted, perform the following steps:

    1. Prepare two integer variables, such as total and pending.

    2. When the cursor opens, set both variables to 0.

    3. Each time a PUT statement executes, increment both total and pending.

    4. Whenever a FLUSH statement executes or the cursor is closed, subtract the third field of the SQLERRD array from pending.

References

See the CLOSE, DECLARE, OPEN, and PUT statements in this manual.

For information about the sqlca structure, see the INFORMIX-ESQL/C Programmer's Manual.

In the Informix Guide to SQL: Tutorial, see the discussion of FLUSH in Chapter 6.

FREE

The FREE statement releases resources that are allocated to a prepared statement or to a cursor.

Syntax

(1 of 2)

Element Purpose Restrictions Syntax

cursor id

Identifier for a cursor

A DECLARE statement must have previously created the cursor.

Identifier, p. 1-966

cursor variable

Host variable that identifies a cursor

Variable must be a character data type. Cursor must have been previously created by a DECLARE statement.

Variable name must conform to language-specific rules for variable names

statement id

Identifier for an SQL statement

The statement identifier must be defined in a previous PREPARE statement. After you release the database-server resources, you cannot use the statement identifier with a DECLARE cursor or with the EXECUTE statement until you prepare the statement again.

PREPARE, p. 1-541

statement id variable

A host variable that identifies an SQL statement

This variable must be defined in a previous PREPARE statement. Variable must be a character data type.

PREPARE, p. 1-541

Usage

The FREE statement releases the resources that were allocated for a prepared statement or a declared cursor in the application-development tool and the database server. Resources are allocated when you prepare a statement or when you open a cursor (see the DECLARE and OPEN statements on pages 1-303 and 1-528, respectively.)

The amount of available memory in the system limits the total number of open cursors and prepared statements that are allowed at one time in one process. Use FREE statement id or FREE statement id variable to release the resources that a prepared statement holds; use FREE cursor id or FREE cursor variable to release resources that a cursor holds.

Freeing a Statement

If you prepared a statement (but did not declare a cursor for it), FREE statement id (or statement id variable) releases the resources in both the application development tool and the database server.

If you declared a cursor for a prepared statement, FREE statement id (or statement id variable) releases only the resources in the application development tool; the cursor can still be used. The resources in the database server are released only when you free the cursor.

After you free a statement, you cannot execute it or declare a cursor for it until you prepare it again.

The following INFORMIX-ESQL/C example shows the sequence of statements that is used to free an implicitly prepared statement:

The following INFORMIX-ESQL/C example shows the sequence of statements that are used to release the resources of an explicitly prepared statement. The first FREE statement in this example frees the cursor. The second FREE statement in this example frees the prepared statement.

Freeing a Cursor

If you declared a cursor for a prepared statement, freeing the cursor releases only the resources in the database server. To release the resources for the statement in the application-development tool, use FREE statement id (or statement id variable).

If a cursor is not declared for a prepared statement, freeing the cursor releases the resources in both the application-development tool and the database server.

After a cursor is freed, it cannot be opened until it is declared again. The cursor should be explicitly closed before it is freed.

For an example of a FREE statement that frees a cursor, see the second example in "Freeing a Statement".

References

See the CLOSE, DECLARE, EXECUTE, EXECUTE IMMEDIATE, and PREPARE statements in this manual.

In the Informix Guide to SQL: Tutorial, see the discussion of the FREE statement in Chapter 5.

GET DESCRIPTOR

Use the GET DESCRIPTOR statement to obtain values from a system-descriptor area.

Syntax

Element Purpose Restrictions Syntax

descriptor

A quoted string that identifies a system-descriptor area from which information is to be obtained

The system-descriptor area must have been allocated in an ALLOCATE DESCRIPTOR statement.

Quoted String, p. 1-1014

descriptor variable

An embedded variable name that holds the value of descriptor

The system-descriptor area identified in descriptor variable must have been allocated in an ALLOCATE DESCRIPTOR statement.

The name of the embedded variable must conform to language-specific rules for variable names.

field host variable

The name of a host variable that receives the contents of the specified field from the system-descriptor area

The field host variable must be an appropriate type to receive the value of the specified field from the system-descriptor area

The name of the field host variable must conform to language-specific rules for variable names.

host variable

The name of a host variable that indicates how many values are described in the system-descriptor area

The host variable must be an integer data type.

The name of the host variable must conform to language-specific rules for variable names.

item number

An unsigned integer that represents one of the occurrences (item descriptors) in the system-descriptor area

The value of item number must be greater than zero and less than the number of occurrences that were specified when the system- descriptor area was allocated with the ALLOCATE DESCRIPTOR statement.

Literal Number, p. 1-1001

item number variable

The name of a host variable that holds the value of item number

The item number variable must be an integer data type.

The name of the item number variable must conform to language-specific rules for variable names.

Usage

The GET DESCRIPTOR statement can be used after you have described SELECT, EXECUTE FUNCTION, and INSERT statements with the DESCRIBE...USING SQL DESCRIPTOR statement. The GET DESCRIPTOR statement can obtain values from a system-descriptor area in the following instances:

If an error occurs during the assignment to any identified host variable, the contents of the host variable are undefined. The host variables that are used in the GET DESCRIPTOR statement must be declared in the INFORMIX-ESQL/C program. See the INFORMIX-ESQL/C Programmer's Manual for information on the role and contents of each field in the system-descriptor area and on how to declare host variables.

Using the COUNT Keyword

Use the COUNT keyword to determine how many values are described in the system-descriptor area. The following INFORMIX-ESQL/C example shows how to use a GET DESCRIPTOR statement with a host variable to determine how many values are described in the system-descriptor area called desc1:

VALUE Clause

Use the VALUE clause to obtain information about a described column or expression or to retrieve values that the database server returns in a system-descriptor area. You can modify values for items after you use the DESCRIBE statement to fill the fields for a SELECT, EXECUTE FUNCTION, or INSERT statement, or you can obtain values for items for which you are providing a description (such as parameters in a WHERE clause).

The item number must be greater than zero and less than the number of occurrences that were specified when you allocated the system-descriptor area with the ALLOCATE DESCRIPTOR statement.

Using the VALUE Clause After a DESCRIBE
After you describe a SELECT, EXECUTE FUNCTION, or INSERT statement with the DESCRIBE...USING SQL DESCRIPTOR statement, the characteristics of each column or expression in the select list of the SELECT statement, the characteristics of the values returned by the EXECUTE FUNCTION statement, or the characteristics of each column in the INSERT statement are returned to the system-descriptor area. Each value in the system-descriptor area describes the characteristics of one returned column or expression. Each field and its possible contents are described in the INFORMIX-ESQL/C Programmer's Manual.

The following INFORMIX-ESQL/C example shows how to use a GET DESCRIPTOR statement to obtain data type information from the demodesc system-descriptor area:

The value that the database server returns into the TYPE field is a defined integer. To evaluate the data type that is returned, test for a specific integer value. The codes for the TYPE field are listed in the description of the SET DESCRIPTOR statement on page 1-702.

X/O
In X/Open mode, the X/Open code is returned to the TYPE field. You cannot mix the two modes because errors can result. For example, if a particular data type is not defined under X/Open mode but is defined for Informix products, executing a GET DESCRIPTOR statement can result in an error.

In X/Open mode, a warning message appears if ILENGTH, DATA, or ITYPE is used. It indicates that these fields are not standard X/Open fields for a system-descriptor area.

For more information about TYPE, ILENGTH, IDATA, and ITYPE, see the dynamic management chapter in the INFORMIX-ESQL/C Programmer's Manual. For more information about programming in X/Open mode, see the preprocessing and compilation syntax in the appropriate Informix SQL API programmer's manual.

If the TYPE field for a fetched value is DECIMAL or MONEY, the database server returns the precision and scale information for a column into the PRECISION and SCALE fields after a DESCRIBE statement is executed. If the TYPE is not DECIMAL or MONEY, the SCALE and PRECISION fields are undefined.

Using the VALUE Clause After a FETCH
Each time your program fetches a row, it must copy the fetched value into host variables so that the data can be used. To accomplish this task, use a GET DESCRIPTOR statement after each fetch of each value in the select list. If three values exist in the select list, you need to use three GET DESCRIPTOR statements after each fetch (assuming you want to read all three values). The item numbers for each of the three GET DESCRIPTOR statements are 1, 2, and 3.

The following INFORMIX-ESQL/C example shows how you can copy data from the DATA field into a host variable (result) after a fetch. For this example, it is predetermined that all returned values are the same data type.

Fetching a Null Value
When you use GET DESCRIPTOR after a fetch, and the fetched value is null, the INDICATOR field is set to -1 (NULL). The value of DATA is undefined if INDICATOR indicates a null value. The host variable into which DATA is copied has an unpredictable value.

Using LENGTH or ILENGTH

If your DATA or IDATA field contains a character string, you must specify a value for LENGTH. If you specify LENGTH=0, LENGTH is automatically set to the maximum length of the string. The DATA or IDATA field might contain a literal character string or a character string that is derived from a character variable of CHAR or VARCHAR data type. This provides a method to determine dynamically the length of a string in the DATA or IDATA field.

If a DESCRIBE statement precedes a GET DESCRIPTOR statement, LENGTH is automatically set to the maximum length of the character field that is specified in your table.

This information is identical for ILENGTH. Use ILENGTH when you create a dynamic program that does not comply with the X/Open standard.

Describing an Opaque-Type Column

The DESCRIBE statement sets the following item-descriptor fields when the column to fetch has an opaque type as its data type:

    This integer value corresponds to a value in the extended_id column of the sysxtdtypes system catalog table.

    This character value corresponds to a value in the name column of the row with the matching extended_id value in the sysxtdtypes system catalog table.

    This integer value is the length, in bytes, of the name of the opaque type.

    This character value corresponds to a value in the owner column of the row with the matching extended_id value in the sysxtdtypes system catalog table.

    This integer value is the length, in bytes, of the owner name for the opaque type.

Use these field names with the GET DESCRIPTOR statement to obtain information about an opaque column. For more information on the sysxtdtypes system catalog table, see Chapter 1 of the Informix Guide to SQL: Syntax.

Describing a Distinct-Type Column

The DESCRIBE statement sets the following item-descriptor fields when the column to fetch has an distinct type as its data type:

    This integer value corresponds to a value in the source column for the row of the sysxtdtypes system catalog table whose extended_id value matches that of the distinct type you are setting. This field is only set if the source data type is an opaque data type.

Use these field names with the GET DESCRIPTOR statement to obtain information about a distinct-type column. For more information on the sysxtdtypes system catalog table, see Chapter 1 of the Informix Guide to SQL: Syntax.

References

See the ALLOCATE DESCRIPTOR, DEALLOCATE DESCRIPTOR, DECLARE, DESCRIBE, EXECUTE, FETCH, OPEN, PREPARE, PUT, and SET DESCRIPTOR statements in this manual for more information about using dynamic SQL statements.

For more information about the system-descriptor area, see the INFORMIX-ESQL/C Programmer's Manual.

GET DIAGNOSTICS

Use the GET DIAGNOSTICS statement to return diagnostic information about executing an SQL statement. The GET DIAGNOSTICS statement uses one of two clauses, as the following list describes:

Syntax

Usage

The GET DIAGNOSTICS statement retrieves selected status information from the diagnostics area and retrieves either count and overflow information or information on a specific exception. The diagnostics area is a data structure that stores diagnostic information about an executed SQL statement.

The GET DIAGNOSTICS statement never changes the contents of the diagnostics area.

Using the SQLSTATE Status Code

When an SQL statement executes, the database server sets a status code is automatically generated. This code represents one of the following exceptions:

The database server stores this status code in a variable called SQLSTATE.

X/O

The SQLSTATE status variable conforms to the ANSI and X/Open standards.

Tip: Informix database servers also store a status code in an Informix-specific variable called SQLCODE and exception information in the SQLCA structure. For more information, see the "INFORMIX-ESQL/C Programmer's Manual."

Class and Subclass Codes
The SQLSTATE status code is a a five-character string that can contain only digits and capital letters. This string has the following two parts:

Figure 1-1 shows the structure of the SQLSTATE code. This example uses the value 08001, where 08 is the class code and 001 is the subclass code. The value 08001 represents the error server rejected the connection.

Figure 1-1
The Structure of the SQLSTATE Status Code

The following table is a quick reference for interpreting class code values.

SQLSTATE Class Code Value Outcome

00

Success

01

Success with warning

02

End of data
not found

> 02

Errors

Support for ANSI Standards
All status codes returned to the SQLSTATE variable are ANSI compliant except in the following cases:

List of SQLSTATE Codes
The following table describes the class codes, subclass codes, and the meaning of all valid warning and error codes associated with the SQLSTATE status variable.

(1 of 4)

Class Subclass Meaning

00

000

Success

01

01

01

01

01

01

01

000

002

003

004

005

006

007

Success with warning

Disconnect error. Transaction rolled back

Null value eliminated in set function

String data, right truncation

Insufficient item descriptor areas

Privilege not revoked

Privilege not granted

01

01

01

01

01

01

01

01

01

01

I01

I03

I04

I05

I06

I07

I08

I09

I10

I11

Database has transactions

ANSI-compliant database selected

INFORMIX-Universal Server database selected

Float to decimal conversion has been used

Informix extension to ANSI-compliant standard syntax

UPDATE/DELETE statement does not have a WHERE clause

An ANSI keyword has been used as a cursor name

Number of items in the select list is not equal to the number in the into list

Database server running in secondary mode

Dataskip is turned on

01

U01

User-defined routine has defined the warning message text

02

000

No data found

07

07

07

07

07

07

07

07

07

000

001

002

003

004

005

006

008

009

Dynamic SQL error

USING clause does not match dynamic parameters

USING clause does not match target specifications

Cursor specification cannot be executed

USING clause is required for dynamic parameters

Prepared statement is not a cursor specification

Restricted data type attribute violation

Invalid descriptor count

Invalid descriptor index

08

08

08

08

08

08

08

08

000

001

002

003

004

006

007

S01

Connection exception

Server rejected the connection

Connection name in use

Connection does not exist

Client unable to establish connection

Transaction rolled back

Transaction state unknown

Communication failure

0A

0A

000

001

Feature not supported

Multiple server transactions

21

21

21

000

S01

S02

Cardinality violation

Insert value list does not match column list

Degree of derived table does not match column list

22

22

22

22

22

22

22

22

22

22

000

001

002

003

005

027

012

019

024

025

Data exception

String data, right truncation

Null value, no indicator parameter

Numeric value out of range

Error in assignment

Data exception trim error

Division by zero

Invalid escape character

Unterminated string

Invalid escape sequence

23

000

Integrity constraint violation

24

000

Invalid cursor state

25

000

Invalid transaction state

2B

000

Dependent privilege descriptors still exist

2D

000

Invalid transaction termination

26

000

Invalid SQL statement identifier

2E

000

Invalid connection name

28

000

Invalid user-authorization specification

33

000

Invalid SQL descriptor name

34

000

Invalid cursor name

35

000

Invalid exception number

37

000

Syntax error or access violation in PREPARE or EXECUTE IMMEDIATE

3C

000

Duplicate cursor name

40

40

000

003

Transaction rollback

Statement completion unknown

42

000

Syntax error or access violation

S0

S0

S0

S0

S0

000

001

002

011

021

Invalid name

Base table or view table already exists

Base table not found

Index already exists

Column already exists

S1

001

Memory allocation failure

IX

000

Informix reserved error message

U0

001

User-defined routine has defined the error message text

Using SQLSTATE in Applications
You can use a variable, called SQLSTATE, that you do not have to declare in your program. SQLSTATE contains the status code that is generated every time your program executes an SQL statement. This status code is essential for exception handling. You can examine the SQLSTATE variable to determine whether an SQL statement was successful. If the SQLSTATE variable indicates that the statement failed, you can execute a GET DIAGNOSTICS statement to obtain additional error information from the diagnostics area.

For an example of how to use an SQLSTATE variable in a program, see "Using GET DIAGNOSTICS for Error Checking".

Statement Clause

Element Purpose Restrictions Syntax

st_var

Host variable that receives status information about the most recent SQL statement. It receives information for the specified status field name.

Data type must match that of the requested field.

Variable name must conform to language-specific rules for variable names.

When retrieving count and overflow information, GET DIAGNOSTICS can deposit the values of the three statement fields into a corresponding host variable. The host-variable data type must be the same as that of the requested field. These three fields are represented by the following keywords.

Field Name Keyword Field
Data Type
Field
Contents
ESQL/C
Host Variable Data Type

MORE

Character

Y or N

char[2]

NUMBER

Integer

1 to 35,000

int

ROW_COUNT

Integer

0 to 999,999,999

int

Using the MORE Keyword

Use the MORE keyword to determine if the most recently executed SQL statement performed the following actions:

    The GET DIAGNOSTICS statement returns a value of N.

    The GET DIAGNOSTICS statement returns a value of Y.

The value of MORE is always N.

Using the NUMBER Keyword

Use the NUMBER keyword to count the number of exceptions that the most recently executed SQL statement placed into the diagnostics area. The NUMBER field can hold a value from 1 to 35,000, to indicate how many exceptions are counted.

Using the ROW_COUNT Keyword

Use the ROW_COUNT keyword to count the number of rows the most recently executed statement processed. The ROW_COUNT field counts the following number of rows:

EXCEPTION Clause

Element Purpose Restrictions Syntax

en_var

Host variable that specifies an exception number for a GET DIAGNOSTICS statement

Variable must contain an integer value limited to a range from 1 to 35,000. Variable data type must be INT or SMALLINT.

Variable name must conform to language-specific rules for variable names.

except_num

Literal integer value that specifies the exception number for a GET DIAGNOSTICS statement. The except_num literal indicates one of the exception values from the number of exceptions returned by the NUMBER field in the Statement clause.

Integer value is limited to a range from 1 to 35,000.

Literal Number, p. 1-1001

ex_var

Host variable that you declare, which receives EXCEPTION information about the most recent SQL statement. Receives information for a specified exception field name.

Data type must match that of the requested field.

Variable name must conform to language-specific rules for variable names.

When GET DIAGNOSTICS retrieves exception information, it deposits the values of each of the seven fields into corresponding host variables. These fields are located in the diagnostics area and are derived from an exception raised by the most recent SQL statement.

The host-variable data type must be the same as that of the requested field. The seven exception information fields are represented by the keywords described in the following table.

Field Name
Keyword
Field
Data Type
Field
Contents
ESQL/C Host Variable
Data Type

RETURNED_SQLSTATE

Character

SQLSTATE value

char[6]

CLASS_ORIGIN

Character

String

char[255]

SUBCLASS_ORIGIN

Character

String

char[255]

INFORMIX_SQLCODE

Integer

SQLCODE value

long int

MESSAGE_TEXT

Character

String

char[8191]

MESSAGE_LENGTH

Integer

Numeric value

int

SERVER_NAME

Character

String

char[255]

CONNECTION_NAME

Character

String

char[255]

The application specifies the exception by number, using either an unsigned integer, except_num, or an integer host variable (an exact numeric with a scale of 0), en_var. An exception with a value of 1 corresponds to the SQLSTATE value set by the most recent SQL statement other than GET DIAGNOSTICS. The association between other exception numbers and other exceptions raised by that SQL statement is undefined. Thus, no set order exists in which the diagnostic area can be filled with exception values. You always get at least one exception, even if the SQLSTATE value indicates success.

If an error occurs within the GET DIAGNOSTICS statement (that is, if an illegal exception number is requested), the Informix internal SQLCODE and SQLSTATE variables are set to the value of that exception. In addition, the GET DIAGNOSTICS fields are undefined.

Using the RETURNED_SQLSTATE Keyword

Use the RETURNED_SQLSTATE keyword to determine the SQLSTATE value that describes the exception.

Using the INFORMIX_SQLCODE Keyword

Use the INFORMIX_SQLCODE keyword to retrieve the value of the Informix-specific status code (SQLCODE) for the associated SQLSTATE (and RETURNED_SQLSTATE) value. The Informix Error Messages manual describes Informix-specific codes.

Using the CLASS_ORIGIN Keyword

Use the CLASS_ORIGIN keyword to retrieve the source of the class portion of the RETURNED_SQLSTATE (and SQLSTATE) value. Possible class origins include the following:

Using the SUBCLASS_ORIGIN Keyword

Use the SUBCLASS_ORIGIN keyword to define the source of the subclass portion of the RETURNED_SQLSTATE (and SQLSTATE) value. Possible subclass origins include the following:

Using the MESSAGE_TEXT Keyword

Use the MESSAGE_TEXT keyword to determine the message text of the exception (for example, an error message). User-defined routines (such as stored routines and external routines) can define their own message text, which you can access text through the MESSAGE_TEXT field.

The following values indicate that a user-defined routine has returned a message that the routine has defined:

Using the MESSAGE_LENGTH Keyword

Use the MESSAGE_LENGTH keyword to determine the length of the current string in the MESSAGE_TEXT field.

Using the SERVER_NAME Keyword

Use the SERVER_NAME keyword to determine the name of the database server associated with the actions of a CONNECT or DATABASE statement.

When the SERVER_NAME Field Is Updated
The GET DIAGNOSTICS statement updates the SERVER_NAME field when the following situations occur:

When the SERVER_NAME Field Is Not Updated
The SERVER_NAME field is not updated when:

The SERVER_NAME field retains the value set in the previous SQL statement. If any of the preceding conditions occur on the first SQL statement that executes, the SERVER_NAME field is blank.

The Contents of the SERVER_NAME Field
The SERVER_NAME field contains different information after you execute the following statements.

Executed Statement SERVER_NAME Field Contents

CONNECT

It contains the name of the database server to which you connect or fail to connect. Field is blank if you do not have a current connection or if you make a default connection.

SET CONNECTION

It contains the name of the database server to which you switch or fail to switch.

DISCONNECT

It contains the name of the database server from which you disconnect or fail to disconnect. If you disconnect and then you execute a DISCONNECT statement for a connection that is not current, the SERVER_NAME field remains unchanged.

DISCONNECT ALL

It sets the field to blank if the statement executes successfully. If the statement does not execute successfully, the SERVER_NAME field contains the names of all the database servers from which you did not disconnect. However, this information does not mean that the connection still exists.

If the CONNECT statement is successful, the SERVER_NAME field is set to one of the following values:

The DATABASE Statement
When you execute a DATABASE statement, the SERVER_NAME field contains the name of the server on which the database resides.

Using the CONNECTION_NAME Keyword

Use the CONNECTION_NAME keyword to specify a name for the connection used in your CONNECT or DATABASE statements.

When the CONNECTION_NAME Keyword Is Updated
GET DIAGNOSTICS updates the CONNECTION_NAME field when the following situations occur:

When CONNECTION_NAME Is Not Updated
The CONNECTION_NAME field is not updated when the following situations occur:

The CONNECTION_NAME field retains the value set in the previous SQL statement. If any of the preceding conditions occur on the first SQL statement that executes, the CONNECTION_NAME field is blank.

The Contents of the CONNECTION_NAME Field
The CONNECTION_NAME field contains different information after you execute the following statements.

Executed Statement CONNECTION_NAME Field Contents

CONNECT

It contains the name of the connection, specified in the CONNECT statement, to which you connect or fail to connect. The field is blank if you do not have a current connection or if you make a default connection.

SET CONNECTION

It contains the name of the connection, specified in the CONNECT statement, to which you switch or fail to switch.

DISCONNECT

It contains the name of the connection, specified in the CONNECT statement, from which you disconnect or fail to disconnect. If you disconnect, and then you execute a DISCONNECT statement for a connection that is not current, the CONNECTION_NAME field remains unchanged.

DISCONNECT ALL

The CONNECTION_NAME field is blank if the statement executes successfully. If the statement does not execute successfully, the CONNECTION_NAME field contains the names of all the connections, specified in your CONNECT statement, from which you did not disconnect. However, this information does not mean that the connection still exists.

If the CONNECT is successful, the CONNECTION_NAME field is set to the following values:

The DATABASE Statement
When you execute a DATABASE statement, the CONNECTION_NAME field is blank.

Using GET DIAGNOSTICS for Error Checking

The GET DIAGNOSTICS statement returns information held in various fields of the diagnostic area. For each field in the diagnostic area that you want to access, you must supply a host variable with a compatible data type.

The following examples illustrate using the GET DIAGNOSTICS statement to display error information. The first example shows an ESQL/C error display routine called disp_sqlstate_err().

References

In Chapter 5 of the Informix Guide to SQL: Tutorial, see the discussion about error-code handling. In addition, refer to the exception-handling chapter of the INFORMIX-ESQL/C Programmer's Manual.




Informix Guide to SQL: Syntax, version 9.1
Copyright © 1998, Informix Software, Inc. All rights reserved.