The DESCRIBE statement and memory allocation

When you use a system-descriptor area to hold columns of prepared SQL statements, the ALLOCATE DESCRIPTOR statement allocates memory for the item descriptors of each column and the DESCRIBE...USING SQL DESCRIPTOR statement allocates memory for the DATA field of each item descriptor.

However, the DESCRIBE...USING SQL DESCRIPTOR statement does not allocate memory for the DATA field of a system-descriptor area when you describe a prepared SELECT statement that fetches data from a column into a host variable of type lvarchar.

Before you fetch lvarchar data into the system-descriptor area, you must explicitly assign memory to the DATA field to hold the column value, as follows:
  1. Declare an lvarchar host variable of the appropriate size.

    Make sure that this variable is not just a pointer but has memory associated with it.

  2. Assign this host variable to the DATA field with the SET DESCRIPTOR statement.

    This SET DESCRIPTOR statement occurs after the DESCRIBE...USING SQL DESCRIPTOR statement but before the FETCH...USING SQL DESCRIPTOR statement.

  3. Execute the FETCH...USING SQL DESCRIPTOR statement to retrieve the column data into the DATA field of the system-descriptor area.
The following code fragment shows the basic steps to allocate memory for an LVARCHAR column called lvarch_col in the table1 table:
EXEC SQL BEGIN DECLARE SECTION;
   lvarchar lvarch_val[50];
   int i;
EXEC SQL END DECLARE SECTION;

EXEC SQL allocate descriptor 'desc';
EXEC SQL prepare stmt1 from 'select opaque_col from table1';
EXEC SQL describe stmt1 using sql descriptor 'desc';
EXEC SQL declare cursor curs1 for stmt1;
EXEC SQL open curs1;
EXEC SQL set descriptor 'desc' value 1 
   data = :lvarch_val, length = 50;

while (1)
   {
   EXEC SQL fetch curs1 using sql descriptor 'desc';
   EXEC SQL get descriptor 'desc' value 1 :lvarch_val;
   printf("Column value is %s\n", lvarch_val);
   
;

   }

The preceding code fragment does not perform exception handling.