Archive

Posts Tagged ‘ODBC’

DECIMAL columns with ODBC

September 16th, 2009 No comments

I had to debug a piece of code recently that in short tried to run a query against a database and get the results through ODBC. The problem was that the DECIMAL columns were reported as being NULL, even though they actually had valid values. The procedure was simple and classic:

  • bind the column
  • set the properties (precision, scale)
  • fetch the data

In code it looked something like:

SQLBindCol( statement, columnIndex, SQL_C_NUMERIC, buffer, bufferLen, indicator );

// set the attributes
SQLHDESC desc;
SQLGetStmtAttr( statement, SQL_ATTR_APP_PARAM_DESC, desc, 0, 0 );
SQLSetDescField( desc, columnIndex, SQL_DESC_TYPE, SQL_C_NUMERIC, 0 );
SQLSetDescField( desc, columnIndex, SQL_DESC_PRECISION, precision, 0 );
SQLSetDescField( desc, columnIndex, SQL_DESC_SCALE, scale, 0 );
SQLSetDescField( desc, columnIndex, SQL_DESC_DATA_PTR, buffer, 0 );

(Error checking and other stuff removed, all variables have proper types and values)

What this lead to is that after the fetch the buffer had the right value in it but the indicator parameter was -1, saying the column is NULL.

After about half a day of banging my head against all the walls I could find trying to figure out what was wrong with this, it finally hit me: there was one more thing I had to set (actually re-set – it was already done in the call to SQLBindCol(), or so I thought). Yep, the indicator field needs to be set again:

SQLSetDescField( desc, columnIndex, SQL_DESC_INDICATOR_PTR, indicator, 0 );
SQLSetDescField( desc, columnIndex, SQL_DESC_OCTET_LENGTH_PTR, indicator, 0 );

Once this was added, the indicator started to get the right value after the fetch – problem fixed.

Maybe I’m an idiot who doesn’t know shit so I’m asking: should I have seen or implied this from the documentation? Is there a hint somewhere in MSDN that I completely missed?

Categories: Programming Tags: , , ,