5

I am using sqlserver to store/search. The problem is I have a form which takes start date and end date to search. If I enter dates after 1753 then no problem. If I enter any date below 1752, I am getting the below exception:

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. 

I know sql server supports date range b/w 1753 and 9999. But I cannot prevent the user from entering dates below 1753. Please help me.

Thanks!

user1016403
  • 12,151
  • 35
  • 108
  • 137

5 Answers5

1

If you need to store dates before 1753 in SQL Server 2005, then you're going to have to store it as text.

If you're storing the date only (no time component), then I'd recommend:

CREATE TABLE Tab (
    /* Other Columns */,
    FunnyDate char(8) not null,
    constraint CK_FunnyDate_MostlyValid CHECK (
        FunnyDate like '[0-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9]')
    /* Other constraints */
)

Which should force it to closely resembly a valid date (in YYYYMMDD format). You might also consider adding a computed column, which represents it as a datetime, if it's convertible to such a value.

If you need to include a time component, I'd recommend storing it in YYYY-MM-DD"T"hh:mm:ss format, and again enforced by a check constraint.

The formats I've recommended above are safely convertible to datetimes without having to consider regional settings.

You can also write stricter check constraints, if needed (e.g. the above does allow a 14th month, for example)

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

I think there are 2 solutions, if you are working with sql server 2005

  1. Keep dates in varchar field
  2. Have different columns for year, month and day.
narek.gevorgyan
  • 4,165
  • 5
  • 32
  • 52
0

If you are using SQL Server 2008 you should use datetime2 datatype.

Even MSDN documentation recomends it!

aF.
  • 64,980
  • 43
  • 135
  • 198
0

How about creating a SQL CLR User defined Datatype? Using .NET we can save dates before 1753 as well.

Check out http://weblogs.sqlteam.com/mladenp/archive/2006/12/16/52754.aspx

vmvadivel
  • 1,041
  • 5
  • 7
0

Depending on the actual format of your time component you can also try setting up specific fields for date components:

periodyear CHAR(4)
periodtype CHAR(2)
period CHAR(2)

This way you can store each segment of the date. For example you can do the following for "March 1745":

periodyear = '1745'
periodtype = '03' (month periodtype - arbitrary and up to you to define)
period = '03' (for 3rd month)

For days of the month you could try using the number of the day in the year or adding in a "day" field.

wergeld
  • 14,332
  • 8
  • 51
  • 81