#include <stdio.h>
#include <stdlib.h>
#include <sql.h>
#include <sqlext.h>
#include <string.h>

int main() {
    HENV   henv;
    HDBC   hdbc;
    char errstate[256] = "99999";
    char errmsg[256];
    SDWORD errcode;
    SWORD sz;

    HSTMT  hstmt;
    int prm_int[1]={100};
    char *call = "{?=CALL PROC1()}";

    SQLAllocEnv(&henv);
    SQLAllocConnect(henv, &hdbc);
    RETCODE retcode = SQLConnect(hdbc, "PostgreSQL", SQL_NTS, "postgres", SQL_NTS, "postgres", SQL_NTS);
    if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) {
        printf("Error : SQLConnect\n");
        exit(1);
    }

    if (SQLAllocStmt(hdbc, &hstmt) != SQL_SUCCESS)  {
        printf("Error : SQLAllocStmt\n");
        exit(1);
    }
    RETCODE RtCode  = SQLBindParameter(
            (SQLHSTMT)     hstmt,
            (SQLSMALLINT)  1,
            (SQLSMALLINT)  SQL_PARAM_OUTPUT,
            (SQLSMALLINT)  SQL_C_LONG,
            (SQLSMALLINT)  SQL_INTEGER,
            (SQLINTEGER)   0,
            (SQLSMALLINT)  0,
            (PTR)          &prm_int,
            (SQLINTEGER)   0,
            (SQLLEN *)     NULL);
    if (RtCode != SQL_SUCCESS)  {
        printf("Error : SQLBindParameter\n");
        exit(1);
    }

	printf("init : %d\n", prm_int[0]);
    if (SQLExecDirect(hstmt, (UCHAR FAR *)call, SQL_NTS) != SQL_SUCCESS)  {
        SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, errstate, &errcode, errmsg, sizeof(errmsg), &sz);
        printf("Error : SQLExecDirect\n");
    	printf("%s(%d) %*s\n", errstate, errcode, (int)sz, errmsg);
        exit(1);
    }
	printf("after: %d\n", prm_int[0]);

    SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
    SQLFreeStmt(hstmt, SQL_DROP);

    SQLTransact(henv, hdbc, SQL_ROLLBACK);
    SQLDisconnect(hdbc);
    SQLFreeConnect(hdbc);
    SQLFreeEnv(henv);

    return 0;
}
