Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server function to return minimum date (January 1, 1753)

I am looking for a SQL Server function to return the minimum value for datetime, namely January 1, 1753. I'd rather not hardcode that date value into my script.

Does anything like that exist? (For comparison, in C#, I could just do DateTime.MinValue) Or would I have to write this myself?

I am using Microsoft SQL Server 2008 Express.

like image 728
Jeremy Avatar asked Sep 29 '10 21:09

Jeremy


People also ask

Why is SQL min date 1753?

SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

How do I find the smallest date in SQL?

SQL MIN() function The aggregate function SQL MIN() is used to find the minimum value or lowest value of a column or expression. This function is useful to determine the smallest of all selected values of a column.

Does MIN function work on dates SQL?

Apparently, SELECT DISTINCT title, MIN(date) FROM table doesn't work. Don't call a column date if you can avoid it. It's only going to cause you problems in the long run.

What is the minimum value for date time field in SQL Server?

Remarks. The minimum valid date for a SqlDateTime structure is January 1, 1753.


2 Answers

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime) 

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime) 

Example Function

create function dbo.DateTimeMinValue() returns datetime as begin     return (select cast(-53690 as datetime)) end 

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue  DateTimeMinValue ----------------------- 1753-01-01 00:00:00.000 
like image 161
D'Arcy Rittich Avatar answered Oct 02 '22 20:10

D'Arcy Rittich


Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

like image 44
Naeem Sarfraz Avatar answered Oct 02 '22 18:10

Naeem Sarfraz