SQL/MX Programming Manual for C and COBOL (G06.24+, H06.03+)

Host Variables in C/C++ Programs
HP NonStop SQL/MX Programming Manual for C and COBOL523627-004
3-16
Variable-Length Character Data
void blank_pad(char *buf, size_t size);
...
int main()
{
EXEC SQL BEGIN DECLARE SECTION;
unsigned NUMERIC (4) hv_prod_num;
char hv_prod_desc[11];
EXEC SQL END DECLARE SECTION;
...
/* Initialize to blank first */
strncpy(hv_prod_desc, " ", sizeof(hv_prod_desc));
/* Then copy the initial value in */
strcpy(hv_prod_desc,"abc"); /* Copy 3 characters */
blank_pad(hv_prod_desc, sizeof(hv_prod_desc) - 1);
EXEC SQL INSERT INTO products (prod_num, prod_desc)
VALUES (:hv_prod_num, :hv_prod_desc);
...
} /* end main */
void blank_pad(char *buf, size_t size)
{
size_t i;
i = strlen(buf);
if (i < size)
memset(&buf[i], ' ', size - i);
buf[size] = '\0';
} /* end blank_pad */
Variable-Length Character Data
In a C/C++ program, you can retrieve from and insert character data into an SQL
VARCHAR column in the same way you do for a char column—by declaring a host
variable as a fixed-length character array. You can also declare a VARCHAR host
variable in an embedded SQL C/C++ program.
Declaring a VARCHAR Host Variable
In addition to the C char data type, SQL-99 provides the VARCHAR data type for host
variables within embedded SQL C/C++ programs. For host variables declared as the
VARCHAR data type, the SQL C/C++ preprocessor generates a C char data type.
When you declare a VARCHAR array as a host variable, the SQL C/C++ preprocessor
by default reserves the last character of the array as a placeholder for a null terminator.
Therefore, declare a VARCHAR array one character longer than the actual number of
required characters.
Note. If you are using MXCI, be sure to blank pad fixed-length character arrays, even when
inserting or updating a null value. If you do not blank pad the array, selected data in MXCI
shows misaligned data. However, the selected data in the embedded SQL program appears
correctly.