#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
#define SMALLER_FIRST 1 //Use this to determine which parameter is bound first.
//Set to 1 to reproduce the failure.
void main(void)
{
SQLHANDLE henv;
SQLHANDLE hdbc;
SQLHANDLE hstmt;
RETCODE rc;
char Statement[50] = {"select title_id from pubs..titles where title = ?"};
char dsn[10] = {"DSNName"};
char user[5] = {"DatabaseUser"};
char pass[5] = {"Password"};
char m_titleid[10] = {"\0"};
char param2[22] = {"The Gourmet Microwave"};
char param1[14] = {"Net Etiquette"};
param1[13] = '\0';
param2[21] = '\0';
long sqlnts = SQL_NTS;
long m_bytesRet = SQL_NTS;
rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
(SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER);
rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
rc = SQLConnect(hdbc, (SQLCHAR *)dsn, SQL_NTS, (SQLCHAR *) user, SQL_NTS,
(SQLCHAR *) pass, SQL_NTS);
rc = SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstmt);
rc = SQLPrepare(hstmt, (SQLCHAR *)Statement, SQL_NTS);
#if SMALLER_FIRST //Put smaller parameter first.
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_WCHAR, 13, 0,
(SQLCHAR*)param1, 13, &sqlnts);
#else
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_WCHAR, 21, 0,
(SQLCHAR*)param2, 21, &sqlnts);
#endif
rc = SQLExecute(hstmt);
rc = SQLFetch(hstmt);
if (rc == SQL_NO_DATA_FOUND)
{
printf("Parameter #1 (%s) returned no data.\n", param1);
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
exit(0);
}
else
{
SQLGetData(hstmt, 1, SQL_C_CHAR, m_titleid, 10, &m_bytesRet);
printf("Title_id for parameter (%s) = %s\n", SMALLER_FIRST?param1:param2, m_titleid);
}
rc = SQLFreeStmt(hstmt, SQL_CLOSE);
memset(m_titleid,0,10);
#if SMALLER_FIRST //Put larger parameter last.
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_WCHAR, 21, 0,
(SQLCHAR*)param2, 21, &sqlnts);
#else
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_WCHAR, 13, 0,
(SQLCHAR*)param1, 13, &sqlnts);
#endif
rc = SQLExecute(hstmt);
rc = SQLFetch(hstmt);
if (rc == SQL_NO_DATA_FOUND)
{
printf("Parameter #2 (%s) returned no data.\n", param2);
SQLFreeStmt(hstmt, SQL_DROP);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
exit(0);
}
else
{
SQLGetData(hstmt, 1, SQL_C_CHAR, m_titleid, 10, &m_bytesRet);
printf("Title_id for parameter (%s) = %s\n", SMALLER_FIRST?param2:param1, m_titleid);
}
rc = SQLFreeStmt(hstmt, SQL_CLOSE);
rc = SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
}