How do I read a MSSQL DateTimeOffset column in a Visual C++ application?

1

I have an Visual C++ (MFC) application using ADO to access a Microsoft SQL Server database. I'd like to start using DateTimeOffset columns but I'm getting an exception.

Here's a code snippet:

HRESULT hRes = pRecordset.CreateInstance(__uuidof(Recordset));
FieldPtr fieldPtr = pRecordset->Fields->GetItem(bstrFieldName);
DataTypeEnum type = fieldPtr->Type;
_variant_t vFieldValue = fieldPtr->Value;

Assigning Value to a _variant_t throws 0x80020008 Bad variable type.

fieldPtr->Type is 146 for DateTimeOffset fields. Understandably, as ADO 2.8 presumably pre-dates this column type, 146 isn't in DataTypeEnum. However, I know that I can access these fields in classic ASP, which is also ADO 2.8.

How do I access this column?

sql-server
visual-c++
ado
datetimeoffset
asked on Stack Overflow Jul 19, 2011 by Robin Minto

1 Answer

1

Microsoft provides support for downlevel clients by casting DateTimeOffset to a string type.

This means that where Provider=SQLOLEDB, DateTimeOffset will be returned as a string. (This explains why I was successfully able to access the field using classic ASP).

If you're using a more recent provider such as SQL Server Native Client 10.0 OLE DB Provider (Provider=SQLNCLI10), you'll need a different approach.

The simplest approach is to cast to a varchar in the SELECT statement:

SELECT CAST(SYSDATETIMEOFFSET() AS VARCHAR(34))

An alternative is to use VARIANT to access the value as a double (dblVal) and convert from that. For example:

HRESULT hRes = pRecordset.CreateInstance(__uuidof(Recordset));
FieldPtr fieldPtr = pRecordset->Fields->GetItem(bstrFieldName);
VARIANT v;
VariantInit(&v);
fieldPtr->get_Value(&v);
_bstr_t bstrTime = v.bstrVal;
VariantClear(&v);

However, I'm not aware of a library that will convert the floating point representation to something more useable so there's some additional work to do there.

answered on Stack Overflow Oct 17, 2011 by Robin Minto • edited Oct 18, 2011 by Robin Minto

User contributions licensed under CC BY-SA 3.0