Sunday, February 19, 2012

Excel to MS SQL Server via OLE - Date problem

Background:
I have Excel files that are not in a good 'data' format so I'm planning to
migrate the data out of Excel into MS SQL server. Since the data is spread
all over the place in the current Excel files, I'll need to write code to
grab the right data, build a select statement, and push the data into SQL
Server.
Current status:
I have working code that pushes the stuff I want into SQL server. Woot!
Problem:
The excel files contain date and time fields. The date cells have values of
39000, etc and the time fields are decimals from 0 to 1. All pretty standard.
When I grab a date field using the following OLE code:
TestDate = Cdat(xlSheet2.Range("D8").Value)
And then display it back, I see an actual date.
When I do the same thing with a time field, I just see the decimal number.
Problem is that when they get to SQL server,
Dates are all: 1/1/1900 12:00:00 AM
Times are: 1/1/1900 with what appears to be the right time.
The SQL server fields are Datetime.
I'm stuck - any suggestions?
TIA.
Doug
ps - I've cross posted in the Excel groupNothing like posting a question to make the answer clear...
My OLE code buids a string that becomes the insert query on the SQL server
side.
The string looks something like:
Insert into tableX(Field1, Field2, Field3) Values ('StringValue',
numericValue)
Two things.
First: I needed to add the date value and time value from Excel into a
single number.
Second: rather than submit the value as a value, I send it as a string ala
Insert into tableX(Field1, Field2) Values ('MyString', '12/31/2008 08:00:00
AM')
poof, works great.
Hope this is of value to others.
Doug
"Doug_F" wrote:
> Background:
> I have Excel files that are not in a good 'data' format so I'm planning to
> migrate the data out of Excel into MS SQL server. Since the data is spread
> all over the place in the current Excel files, I'll need to write code to
> grab the right data, build a select statement, and push the data into SQL
> Server.
> Current status:
> I have working code that pushes the stuff I want into SQL server. Woot!
> Problem:
> The excel files contain date and time fields. The date cells have values of
> 39000, etc and the time fields are decimals from 0 to 1. All pretty standard.
> When I grab a date field using the following OLE code:
> TestDate = Cdat(xlSheet2.Range("D8").Value)
> And then display it back, I see an actual date.
> When I do the same thing with a time field, I just see the decimal number.
> Problem is that when they get to SQL server,
> Dates are all: 1/1/1900 12:00:00 AM
> Times are: 1/1/1900 with what appears to be the right time.
> The SQL server fields are Datetime.
> I'm stuck - any suggestions?
> TIA.
> Doug
> ps - I've cross posted in the Excel group

No comments:

Post a Comment