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

/*----------------------------------------------------------------*/
/*								  */
/*  Example of binding by data variables (by name)		  */
/*								  */
/*  Run EMP.SQL via SQLTALK to initialize tables and data	  */
/*								  */
/*----------------------------------------------------------------*/

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

	  main()
{
	  char	    name[21];		/* employe name buffer	  */
	  int	    first;		/* first number 	  */
	  int	    second;		/* second number	  */
	  int	    i;			/* integer counter	  */

static	  char	    selcmd [] = 	/* SQL SELECT statement   */
"SELECT EMP_NAME FROM EMP WHERE EMP_NO >= :THIS AND EMP_NO <= :THAT";

  /* 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");

  /*
    BIND EACH DATA VARIABLE BY DATA NAME
  */

  if (rcd = sqlbnd(cur, "this", 0, (char*)&first, sizeof(first), 0, SQLPUIN))
    failure("FIRST BIND");

  if (rcd = sqlbnd(cur, "that", 0,(char*)&second, sizeof(second), 0, SQLPUIN))
    failure("SECOND BIND");

  /*
    EXECUTE SELECT STATEMENT
  */

  for (i = 1; i < 4; i++)      /* select employe number by 1000's */
  {
    first = i * 1000;
    second = first + 999;
    printf("\nEmployes in department %d\n",first);

    if (sqlexe(cur))
      failure("EXECUTING SELECT");

    /*
      FETCH DATA
    */

    for (;;)
    {
      memset(name,'\0',sizeof(name));	/* clear employe name buf */
      if (rcd = sqlfet(cur))		/* fetch the data	  */
	break;
      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");
}
	  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);
}
