#define UNICODE
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <stdio.h>
#include <string.h>
main ()
{
HSTMT hstmt;
HENV henv;
HDBC hdbc;
SDWORD cbValueMax;
SQLRETURN sr;
wchar_t buffer[200];
long keyval;
BYTE outbuff[102];
SQLINTEGER StrLen_or_Ind1 = sizeof( long ), StrLen_or_Ind2;
//Allocate environment handle.
sr = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
//Set the ODBC version.
sr = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
//Allocate connection handle.
sr = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
//Connect.
sr=SQLConnect(hdbc,L"LocalServer",SQL_NTS,L"sa",SQL_NTS,L"",SQL_NTS);
//Allocate statement handle.
sr = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
wcscpy( buffer, L"select * from ntesttab" );
cbValueMax = strlen( ( char * ) buffer);
memset( outbuff, 0, 100 );
//Execute the statement.
sr = SQLExecDirect(hstmt, buffer, SQL_NTS );
//Bind the columns.
sr = SQLBindCol( hstmt, 1, SQL_C_LONG, & keyval, sizeof( long ), & StrLen_or_Ind1 );
//Here we are binding the WCHAR column to SQL_C_DEFAULT.
//If you do this, you will see that the value in outbuff is truncated.
//You will see the truncation only when you have some Unicode data.
//Also, the test table ntesttab has a field which is nchar(10).
//So StrLen_or_Ind2 should report 20, but due to this bug it will
//report 10.
sr = SQLBindCol( hstmt, 2, SQL_C_DEFAULT, & outbuff, 100, & StrLen_or_Ind2 );
//Comment the above, and uncomment the following line to correct
//this problem. If you bind it to SQL_C_WCHAR, the outbuff will
//contain Unicode data and StrLen_or_Ind2 will correctly report 20.
//sr = SQLBindCol( hstmt, 2, SQL_C_WCHAR, & outbuff, 100, & StrLen_or_Ind2 );
//Fetch the data.
sr = SQLFetch( hstmt );
//Examine the memory for outbuff here to see the returned value as char, not wchar.
//Free connection/statement/environment.
SQLFreeStmt( hstmt, SQL_CLOSE );
SQLFreeStmt( hstmt, SQL_DROP );
SQLDisconnect( hdbc );
SQLFreeHandle( SQL_HANDLE_DBC, hdbc );
SQLFreeHandle( SQL_HANDLE_ENV, henv );
return (0);
}