How do I read a MSSQL DateTimeOffset column in a Visual C++ application?
I have an Visual C++ (MFC) application using ADO to access a Microsoft SQL Server database. I'd like to start using D开发者_如何学GoateTimeOffset 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?
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.
精彩评论