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

/*----------------------------------------------------------------*/
/*  Example of fetch of multiple fields 			  */
/*								  */
/*  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	  pline[80];	/* employe name buffer	  */
char*     cp; 		/* -> pline		  */
SQLTSLC   col;		/* column number	  */
SQLTNSI   nsi;		/* number of select items */

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

  /*
  ** 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
  */

  cp = pline;				/* set -> to print line   */

  sqlnsi(cur,&nsi);	   /* OPTIONAL: could hard code 3 instead */

  for (col = 1; col <= nsi; col++)
  {
    if (sqlssb(cur, col, SQLPBUF, cp, 20, 0, SQLNPTR, SQLNPTR))
      failure("SET SELECT BUFFER");
    cp += 20;
  }

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

  /*
  ** FETCH DATA
  */

  for (;;)
  {
    memset(pline,' ',sizeof(pline));	/* clear employe name buf */

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

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

  if (rcd != FETEEOF)			/* 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);
}
