Example: SQL routine exception

In this application example, a stored procedure signals an error when an input value is out of range.

EXEC SQL CREATE PROCEDURE check_input (IN p1 INT)
LANGUAGE SQL READS SQL DATA
test: BEGIN
	IF p1< 0 THEN
		SIGNAL SQLSTATE VALUE '99999'
			SET MESSAGE_TEXT = 'Bad input value';
		END IF
END test;

The calling application checks for a failure and retrieves the information about the failure from the SQL diagnostics area:

char SQLSTATE[6]; /* Stand-alone sqlstate */
long int SQLCODE; /* Stand-alone sqlcode */

long int hv1;
char hv2[6];
char hv3[256];

hv1 = -1;
EXEC SQL CALL check_input(:hv1);

if (strncmp(SQLSTATE, "99999", 5) == 0)
{
  EXEC SQL GET DIAGNOSTICS CONDITION 1
    :hv2 = RETURNED_SQLSTATE,
    :hv3 = MESSAGE_TEXT;
}
else
{
}