I am writing some T-SQL which needs to enforce a minimum date value onto some null fields:
DECLARE @epoch DATETIME;
set @epoch='1900-01-01';
select min = ISNULL(ValidFromDate,@epoch)
Is the string ‘1900-01-01’ always going to return a datetime of Jan 1 1900 in any environment or will SQL server try to parse the string according to local culture rules?
If that’s not good enough, what is the recommended way of specifying a particular date/time in T-SQL?
The best format for string-based dates is the ISO-8601 standard format.
For
DATETIMEvariables and columns, this is eitherYYYYMMDD(for dates without time; without any dashes!) orYYYY-MM-DDTHH:MM:SS(date + time).Contrary to popular belief,
YYYY-MM-DDforDATETIMEvariables is NOT language-/dateformat-independent! If you try this, the secondCASTwill result in an error:but this will work:
This is the best format since it’s indepdendent of your language and dateformat settings in SQL Server.
For SQL Server 2008 and columns of type
DATE(just date – no time), the format can also beYYYY-MM-DD(with the dashes) and that works for all settings, too.Why there is such a difference between
DATEandDATETIMEis beyond me – that’s just the way it is for now!See Tibor Karaszi’s excellent The Ultimate Guide to the DateTime data types for even more details and examples.