views:

89

answers:

3

I used the standard import / export tool to bring a table into my SQL database. The dates all came over as CHAR types. Now, I keep getting a conversion error stating the CHAR to datetime resulted in an out of range condition. Help please.

A: 

Fields of type CHAR(x) in SQL Server will be padded with spaces to their fixed length, e.g. if you have CHAR(20) and you have a date like "2009-04-20" in it, the field will really contain "2009-04-20 " and that might cause trouble when converting to datetime.

Also, if your CHAR field is totally empty, it might not be able to convert to a valid datetime, either.

Solutions:

a) You could change the datatype for your columns to VARCHAR(x) and thus get rid of the most likely unnecessary padding:

ALTER TABLE YourTable
  ALTER COLUMN YourColumnName VARCHAR(x)

b) You could make sure to check for empty CHAR(x) field values and not convert those (or pick a default datetime value for those)

c) You could trim the CHAR(x) fields to remove unnecessary padding:

CONVERT(LTRIM(RTRIM(YourFieldName)), ......)

Cheers!

Marc

marc_s
Thanks guys ! Got it working.
A: 

As well as the solution from marc_s, check for out of range values.

This might explain why it upsized as char not datetime... you may have a date < 1753

This only applies to SQL Server 2005 and before, SQL Server 2008 has datetime2

gbn
SQL Server upsizing has been a great way to reveal data entry errors in date fields, where the year 2000 got entered as the year 200 and so forth. Since then, I've been using input masks that require 4 digits, even though I kind of hate input masks (users don't seem to hate them nearly as much as I do).
David-W-Fenton
@David W. Fenton: When targeting the Access Database Engine I trust you have a CHECK constraint or Validation Rule on the column to do some sensible date range checking.
onedaywhen
A: 

It is recommended to use the SQL Server Migration Assistant (SSMA) rather than the upsizing wizard built into MS Access. Definitely less painful.

Mitch Wheat