SQL/MP Programming Manual for C

Data Retrieval and Modification
HP NonStop SQL/MP Programming Manual for C429847-008
4-14
Using SQL Cursors
Using SQL Cursors
An SQL cursor is a named pointer that a host-language program (C, COBOL, Pascal,
or TAL) can use to access a set of rows in a table or view, one row at time. Using a
cursor, a program can process rows in the same way it might process records in a
sequential file. The program can test the data in each row at the current cursor position
and then if the data meets certain criteria, the program can display, update, delete, or
ignore the row.
Example 4-1 shows the steps that you follow to declare and use a static SQL cursor in
a C program. A cursor operation must run each statement in this specified order. All
steps are required, even if you run the FETCH statement only once to retrieve a single
row.
Example 4-1. Using a Static SQL Cursor in a C Program
/* C source file */
EXEC SQL BEGIN DECLARE SECTION ;
• • • /* Declare host variable(s). */
EXEC SQL END DECLARE SECTION ;
• • •
EXEC SQL DECLARE cursor1 CURSOR FOR
SELECT column1, column2, column n
FROM =table
WHERE column1 = :hostvar_find_row ;
• • •
void find_row(void)
{
• • •
hostvar_find_row = initial_value ; /* Initialize the host variable(s). */
• • •
EXEC SQL OPEN cursor1 ; /* Open the cursor. */
/* Fetch data from a row into the host variable(s). */
EXEC SQL FETCH cursor1
INTO :hostvar_1, :hostvar_2, :hostvar n ;
• • • /* Process the row values in the host variable(s). */
• • • /* Branch back to fetch another row. */
EXEC SQL CLOSE cursor1 ; /* Close the cursor. */
}
009CDT .CDD
1
2
3
4
5
6
7
8