Getting Started with Legacy Pro*C Maintenance — Host Variables, Indicator Variables and NULL, SQLCA, and Cursors
What you need to know when you first inherit old Oracle Pro*C code — host variables, indicator variables and NULL handling, checking errors and row counts with SQLCA, PREPARE-based cursors, and common pitfalls — with a complete runnable example.
Open up an old batch system in finance, manufacturing or the public sector and you will still find plenty of .pc files: C code with EXEC SQL ... statements mixed in. These are Oracle Pro*C programs. Hardly anyone writes new ones, but they often run core batch jobs that work well, so nobody throws them away either. As a result, many developers end up being asked to "just maintain" them.
The trouble is that Pro*C sits halfway between C and SQL, so at first it is hard to tell where the C rules end and the Oracle rules begin. This article walks through the four things you really need to read and change legacy Pro*C code — host variables, indicator variables (NULL handling), SQLCA (errors and row counts) and cursors — and ties them together in one runnable example.
How Does Pro*C Work?
Pro*C is a precompiler. It turns the EXEC SQL statements in a .pc file into calls to the Oracle client library, producing a plain C file (.c), which you then compile like any other C program.
# 1) Precompile: emp_list.pc -> emp_list.c
proc iname=emp_list.pc oname=emp_list.c
# 2) Compile and link
gcc -o emp_list emp_list.c \
-I$ORACLE_HOME/precomp/public \
-L$ORACLE_HOME/lib -lclntsh
Knowing this explains two things:
- Compiler errors sometimes refer to line numbers in the generated
.cfile, not the.pcfile. Opening the generated file usually makes the cause obvious. - Some statements, such as
EXEC SQL WHENEVER, are applied at precompile time, in source order, not at run time. We come back to this as a pitfall below.
Host Variables: The Bridge Between C and SQL
A host variable is a C variable used inside an SQL statement. Inside SQL you prefix its name with a colon (:).
EXEC SQL BEGIN DECLARE SECTION;
int emp_no;
char emp_name[21]; /* VARCHAR2(20) + 1 byte for the trailing NUL */
double salary;
EXEC SQL END DECLARE SECTION;
EXEC SQL SELECT ename, sal
INTO :emp_name, :salary
FROM emp
WHERE empno = :emp_no;
Things to keep in mind:
- DECLARE SECTION: modern Pro*C works without it in C mode, but it is required in C++ mode (
code=cpp) or withparse=none. Most legacy code uses it, so following the existing style is the safe choice. - String size: when you receive a string into a
chararray a NUL is appended, so make the array one byte larger than the column length. - The
VARCHARpseudo-type: Pro*C has its own type, e.g.VARCHAR name[21];. The precompiler turns it into a struct withlen(length) andarr(contents), andarris not NUL-terminated. That is why lines likename.arr[name.len] = '\0';show up so often in legacy code. - Trailing blanks: with the default setting (
char_map=charz), a value received into achararray is blank-padded to the array length and then NUL-terminated. You therefore need to trim trailing spaces before comparing strings.
Indicator Variables and NULL Handling
C has no notion of "no value". An int is always some number, and a char array is always some string. So you need a separate variable to tell the C side that a column was NULL: the indicator variable.
- Its type is
short(2 bytes). - You write it right after the host variable, either as
:comm :comm_indor, more readably, with theINDICATORkeyword::comm INDICATOR :comm_ind. Both mean the same thing.
What the indicator means after SELECT/FETCH
| Value | Meaning |
|---|---|
-1 |
The column is NULL. The host variable's value must not be trusted |
0 |
The value arrived intact, without truncation |
> 0 |
The value was longer than the host variable and was truncated. The indicator holds the original length |
-2 |
The value was truncated and the original length could not be determined |
EXEC SQL SELECT comm
INTO :comm INDICATOR :comm_ind
FROM emp
WHERE empno = :emp_no;
if (comm_ind == -1) {
printf("No commission\n"); /* do not use comm */
} else {
printf("Commission: %.2f\n", comm);
}
Writing NULL with INSERT/UPDATE
You also use indicators to store NULL. If the indicator is -1, NULL is stored no matter what the host variable holds; if it is 0 or more, the host variable's value is stored.
comm_ind = -1; /* store NULL */
EXEC SQL UPDATE emp
SET comm = :comm INDICATOR :comm_ind
WHERE empno = :emp_no;
What if you forget the indicator?
If you fetch a nullable column without an indicator, the default settings raise ORA-01405: fetched column value is NULL (sqlca.sqlcode is -1405). It typically surfaces when a column that was always filled suddenly receives a single NULL and a batch job stops — which makes it a frequent cause of incidents in legacy systems.
NVL or an indicator?
Converting in SQL with something like NVL(comm, 0) also avoids the error without an indicator. Choose between the two based on meaning rather than performance:
- NVL is simple when you are sure that "treat NULL as 0" is correct for the business.
- An indicator is necessary when "the value is 0" and "there is no value" must be distinguished — a 0% discount and an unregistered discount rate may mean different things.
SQLCA: A Report on the SQL You Just Ran
After every SQL statement, Pro*C records the result in a struct called sqlca, the SQL Communications Area (SQLCA). You include it with one line:
EXEC SQL INCLUDE SQLCA;
The most commonly used fields are:
| Field | Meaning |
|---|---|
sqlca.sqlcode |
0 success, < 0 error (the negated ORA number), > 0 an exceptional but normal condition (typically 1403, no data found) |
sqlca.sqlerrm.sqlerrmc |
Error message (holds at most 70 characters) |
sqlca.sqlerrm.sqlerrml |
Length of that message |
sqlca.sqlerrd[2] |
Number of rows processed (UPDATE/DELETE count, cumulative FETCH count) |
sqlca.sqlwarn[0] |
'W' if any warning was set |
A few points to watch:
1403is not an error. It is the normal signal thatSELECT ... INTOfound nothing or that a cursor has no more rows. (If you precompile in ANSI mode,mode=ansi, it is100instead. Check which options the existing code is built with first.)- Messages are truncated.
sqlerrmcholds only 70 characters; use thesqlglm()function when you need the full message. sqlerrd[2]is cumulative for FETCH. It is the total number of rows fetched since the cursor was opened, not the count for the latest FETCH. This is especially confusing in code that uses array fetches.- Check UPDATE/DELETE by row count. Matching no rows is not an error, so get into the habit of checking
sqlerrd[2]to confirm the change actually happened. - If several
.pcfiles share onesqlca, define#define SQLCA_STORAGE_CLASS externbefore the include in every file but one to avoid duplicate definitions.
Cursors: Reading Many Rows One at a Time
SELECT ... INTO is only for queries that return exactly one row (two or more rows raise ORA-01422). To process many rows you use a cursor. The sequence is always the same:
- DECLARE: give the SELECT a cursor name
- OPEN: run the query and prepare the result set
- FETCH: copy one row (or several) into host variables; when done,
sqlcode == 1403 - CLOSE: close the cursor and release its resources
If the SQL is fixed, you can declare it directly with DECLARE emp_cur CURSOR FOR SELECT .... Legacy batch code, however, often has to assemble partition names or conditions at run time, so you frequently see SQL built as a string and then PREPAREd (dynamic SQL).
A Complete Runnable Example
This program takes a department number and prints each employee's number, name and commission. It assumes the commission may be NULL, and that employee number and name are NOT NULL columns.
/* emp_list.pc */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
char userid[128];
char sql_text[512];
int dept_no;
int emp_no;
char emp_name[21];
double comm;
short comm_ind;
EXEC SQL END DECLARE SECTION;
/* Trim trailing blanks: needed with the default char_map=charz */
static void rtrim(char *s)
{
size_t n = strlen(s);
while (n > 0 && s[n - 1] == ' ')
s[--n] = '\0';
}
/* Print the error, roll back and exit */
static void sql_error(const char *where)
{
char msg[512];
size_t buf_len = sizeof(msg);
size_t msg_len = 0;
EXEC SQL WHENEVER SQLERROR CONTINUE; /* avoid an endless loop if ROLLBACK fails */
sqlglm(msg, &buf_len, &msg_len); /* full message, no 70-char limit */
fprintf(stderr, "[%s] sqlcode=%ld %.*s\n",
where, (long)sqlca.sqlcode, (int)msg_len, msg);
EXEC SQL ROLLBACK WORK RELEASE;
exit(1);
}
int main(int argc, char *argv[])
{
const char *conn = getenv("ORA_CONN"); /* e.g. user/password@service */
if (conn == NULL || argc < 2) {
fprintf(stderr, "usage: ORA_CONN=user/pass@db %s <dept_no>\n", argv[0]);
return 1;
}
snprintf(userid, sizeof(userid), "%s", conn);
dept_no = atoi(argv[1]);
EXEC SQL CONNECT :userid;
if (sqlca.sqlcode != 0) sql_error("CONNECT");
/* Pass values as bind variables (:dno), not by pasting them into the string */
snprintf(sql_text, sizeof(sql_text),
"SELECT empno, ename, comm FROM emp "
"WHERE deptno = :dno ORDER BY empno");
EXEC SQL PREPARE emp_stmt FROM :sql_text;
if (sqlca.sqlcode != 0) sql_error("PREPARE");
EXEC SQL DECLARE emp_cur CURSOR FOR emp_stmt;
EXEC SQL OPEN emp_cur USING :dept_no;
if (sqlca.sqlcode != 0) sql_error("OPEN");
for (;;) {
EXEC SQL FETCH emp_cur
INTO :emp_no, :emp_name, :comm INDICATOR :comm_ind;
if (sqlca.sqlcode == 1403) break; /* no more rows: normal end */
if (sqlca.sqlcode < 0) sql_error("FETCH");
rtrim(emp_name);
if (comm_ind == -1)
printf("%6d %-20s %10s\n", emp_no, emp_name, "(none)");
else
printf("%6d %-20s %10.2f\n", emp_no, emp_name, comm);
}
printf("Total: %ld rows\n", (long)sqlca.sqlerrd[2]); /* cumulative FETCH count */
EXEC SQL CLOSE emp_cur;
EXEC SQL COMMIT WORK RELEASE; /* disconnect */
return 0;
}
Build and run it like this:
proc iname=emp_list.pc oname=emp_list.c
gcc -o emp_list emp_list.c -I$ORACLE_HOME/precomp/public -L$ORACLE_HOME/lib -lclntsh
ORA_CONN='user/password@service' ./emp_list 30
What to notice in the example:
- Bind variables:
:dnoindeptno = :dnois a placeholder filled byOPEN ... USING :dept_no. Pasting values into the string withsprintfopens the door to SQL injection, and Oracle has to re-parse the statement from scratch (a hard parse) every time the value changes, which adds load. - When PREPARE is really needed: table and partition names cannot be bind variables. Build only those parts as strings, and validate the value against a fixed list or numeric range before inserting it.
- From error handling to exit: on error the program logs the message, rolls back and exits; on success it closes the cursor and commits.
Common Pitfalls and How to Check for Them
1. WHENEVER applies in source order
A declaration like EXEC SQL WHENEVER SQLERROR GOTO err; applies at precompile time to every SQL statement written below it, regardless of the control flow. A declaration in function A can affect function B further down the file. If you declare WHENEVER NOT FOUND DO break; inside a loop, a break is also generated for later SQL outside the loop, which can cause compile errors. Before changing an SQL statement, find every WHENEVER above it.
2. An endless loop inside the error handler
If WHENEVER SQLERROR DO sql_error(); is still active and the ROLLBACK inside sql_error() fails, sql_error() can be called again and again. Switching to WHENEVER SQLERROR CONTINUE on the first line of the handler, as in the example, prevents this.
3. String buffer size and truncation
It is common for a column to be widened while the C array stays the same size. With an indicator, truncation shows up as a positive value; without one, depending on the settings, you may get an ORA-01406 (truncation) error. When a table definition changes, search the related .pc files for the array sizes too. Remember that multibyte characters such as Korean may need more bytes than characters, depending on the database character set.
4. Comparisons failing because of trailing blanks
If strcmp(code, "A01") == 0 fails for no apparent reason, trailing blanks are the likely culprit. When debugging, print the value in brackets, e.g. printf("[%s]\n", code);, so the spaces become visible.
5. Not closing cursors
If an error path skips CLOSE, cursors pile up until you hit ORA-01000: maximum open cursors exceeded. Conversely, fetching from a closed or never-opened cursor raises ORA-01001: invalid cursor. Make sure the cursor is closed on every exit path.
6. Treating 1403 as an error
Writing if (sqlca.sqlcode != 0) handle_error(); right after a FETCH treats the normal end after the last row as an error. After FETCH and SELECT ... INTO, check for 1403 separately first.
7. A semicolon at the end of a macro
With #define SQL_CD sqlca.sqlcode;, the expression if (SQL_CD != 0) expands to if (sqlca.sqlcode; != 0) and does not compile. It is a surprisingly common mistake in legacy code.
Summary: A Checklist for Pro*C Code You Have Just Inherited
- I checked the
procoptions in the build script first (mode,char_map,code,parse). - Every nullable column has an indicator variable (or an intentional NVL).
- Every string host variable is at least the current column length (in bytes) + 1.
- Trailing blanks are handled before string comparisons.
- After FETCH and
SELECT ... INTO,1403is distinguished from errors. - After UPDATE/DELETE, the row count is checked with
sqlerrd[2]. - I checked every
WHENEVERdeclaration above the SQL I am about to change. - Cursors are closed on every exit path, and the connection is released after commit/rollback.
- Values are passed as bind variables, and anything built into the SQL string is validated.
Pro*C code may look dated, but it is usually code that has handled a company's core business for many years. Once you understand the principles it is more regular than it looks, and following the checklist above prevents a good share of the incidents that arise during maintenance. If you are looking for help maintaining a legacy system like Pro*C, or are considering migrating it to Java or another technology, contact Springuptech. We will review the current code with you and suggest a realistic path forward.
※ This article expands on our lead engineer's earlier personal blog posts (in Korean): "Pro*C 호스트변수, 표지변수", "Pro*C", "Pro-C 커서 패치 예제".
Jaeyong Roh
Lead engineer at Springuptech · 22 years in software engineering
Have a project related to this topic?
Even if it is just an idea, we will help you work out what is possible.