在T-SQL中指定给定日期的正确方法 [英] Correct way of specifying a given date in T-SQL

查看:143
本文介绍了在T-SQL中指定给定日期的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些T-SQL,需要在一些空字段上执行最小日期值:

  DECLARE @epoch约会时间; 
set @ epoch ='1900-01-01';
选择min = ISNULL(ValidFromDate,@ epoch)

字符串'1900-01 -01'总是要在任何环境中返回1900年1月1日的datetime,否则SQL Server会尝试根据本地文化规则解析字符串?



如果不是很好足够的,在T-SQL中指定特定日期/时间的推荐方法是什么?

解决方案

基于日期的是ISO-8601标准格式。



对于 DATETIME 变量和列,这是 YYYYMMDD (日期没有时间;没有任何破折号)或 YYYY-MM-DDTHH:MM:SS (日期+时间)



与普遍的信念相反, YYYY-MM-DD DATETIME 变量是 language- / dateformat-independent!如果您尝试这样做,第二个 CAST 会导致错误:

  SET LANGUAGE us_english 
SELECT CAST('2011-07-20'As DATETIME)

SET LANGUAGE british
SELECT CAST('2011-07-20'AS DATETIME)

但这可以工作:

  SET LANGUAGE british 
SELECT CAST('20110720'as DATETIME)

这是最好的格式,因为它在SQL Server中独立于您的语言和日期格式设置。



对于SQL Server 2008和类型为 DATE (只是日期 - 没有时间),格式也可以是 YYYY-MM-DD (带破折号),也适用于所有设置。



为什么 DATE DATETIME 超出了我 - 这就是现在的方式!



请参阅Tibor Karaszi的优秀 DateTime数据类型的终极指南,以获得更多的细节和例子。


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 DATETIME variables and columns, this is either YYYYMMDD (for dates without time; without any dashes!) or YYYY-MM-DDTHH:MM:SS (date + time).

Contrary to popular belief, YYYY-MM-DD for DATETIME variables is NOT language-/dateformat-independent! If you try this, the second CAST will result in an error:

SET LANGUAGE us_english
SELECT CAST('2011-07-20' AS DATETIME)

SET LANGUAGE british
SELECT CAST('2011-07-20' AS DATETIME)

but this will work:

SET LANGUAGE british
SELECT CAST('20110720' AS DATETIME)

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 be YYYY-MM-DD (with the dashes) and that works for all settings, too.

Why there is such a difference between DATE and DATETIME is 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.

这篇关于在T-SQL中指定给定日期的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆