#include <stdio.h>
#include "sql.h"

/*----------------------------------------------------------------*/
/*  Example of a simple fetch					  */
/*  Run EMP.SQL via MSQL to initialize tables and data	          */
/*----------------------------------------------------------------*/

SQLTCUR   cur;		/* SQLBASE cursor number  */
SQLTRCD   rcd;		/* error number 	  */
char	  errmsg[SQLMERR];	/* error msg text buffer  */

void failure(char *ep);

int main( void ) {

char name[21];		/* employe name buffer	  */

static char selcmd [] = 	/* SQL SELECT statement   */
"SELECT EMP_NAME FROM EMP ORDER BY EMP_NAME";

  /*
  ** CONNECT TO THE DATABASE
  */
  if (rcd = sqlcnc(&cur, "SQLBASE", 0, NULL)) {
    sqlerr(rcd, errmsg);		/* get error message text */
    printf("%s \n",errmsg);
    exit(1);
  }

  /*
  ** COMPILE SELECT STATEMENT
  */
  if (sqlcom(cur, selcmd, 0))
    failure("SELECT COMPILE");

  /*
  ** SET UP SELECT BUFFER
  */
  if (sqlssb(cur, 1, SQLPBUF, name, 20, 0, SQLNPTR, SQLNPTR))
    failure("SET SELECT BUFFER");

  /*
  ** EXECUTE SELECT STATEMENT
  */
  if (sqlexe(cur))
    failure("EXECUTING SELECT");

  /*
  ** FETCH DATA
  */
  for (;;) {
    memset(name,' ',20);		/* clear employe name buf */

    if (rcd = sqlfet(cur))		/* fetch the data	  */
      break;

    name[20] = '\0';
    printf("%s \n", name);		/* print employe name	  */
  }

  if (rcd != 1) 			/* failure on fetch	  */
    failure("FETCH");

  /*
  ** DISCONNECT FROM THE DATABASE
  */
  if (rcd = sqldis(cur))
    failure("DISCONNECT");

  return( 0 );
}

void failure(char *ep) {

SQLTEPO epo;		/* error position	  */

  printf("Failure on %s \n", ep);
  sqlrcd(cur, &rcd);			/* get the error	  */
  sqlepo(cur, &epo);			/* get error position	  */
  sqlerr(rcd, errmsg);			/* get error message text */
  sqldis(cur);
  printf("%s (error: %u, position: %u) \n",errmsg,rcd,epo);
  exit(1);
}
