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

/*----------------------------------------------------------------*/
/*								  */
/*  Example of describe operation				  */
/*								  */
/*  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  */

	  main()
{
	  char	    pline[80];		/* employe name buffer	  */
	  char*     cp; 		/* -> pline		  */
	  SQLTSLC   col;		/* column number	  */
	  SQLTNSI   nsi;		/* number of select items */
	  SQLTDDT   ddt;		/* database data type	  */
	  SQLTPDL   pdl;		/* program data length	  */
	  SQLTCHL   chl;		/* length of col header   */

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 -> print line	  */
  memset(cp,' ',sizeof(pline)); 	/* column heading	  */

  for (col = 1; col <= 3; col++)
  {
    if (sqldes(cur, col, &ddt, &pdl, cp, &chl, SQLNPTR, SQLNPTR))
      failure("SELECT DESCRIBE");
    if (sqlssb(cur, col, SQLPBUF, cp, pdl, 0, SQLNPTR, SQLNPTR))
      failure("SET SELECT BUFFER");
    cp += (pdl + 1);
  }

  pline[70] = '\0';		      /* string terminator	*/
  printf("%s \n\n", pline);	      /* print column headings	*/

  /*
    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[70] = '\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");
}
	  failure(ep)
	  char*     ep; 		/* -> failure msg string  */
{
	  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);
}
