我注意到将字符串转换为日期和日期时间格式时出现了一些奇怪的行为......见下文:
select datename(M,'2016-02-04')
select datename(M,'2016-02-04 14:42:26')
SELECT datename(M,Cast('2016-02-04' as Date))
SELECT datename(M,CAST('2016-02-04 14:42:26' as DateTime))
SELECT Cast('2016-02-04' as Date)
SELECT CAST('2016-02-04 14:42:26' as DateTime)
SELECT CAST('2016-02-04 14:42:26' as SmallDateTime)
SELECT CONVERT(DateTime,'2016-02-04 14:42:26')
结果:
February
February
February
April
2016-02-04
2016-04-02 14:42:26.000
2016-04-02 14:42:26.000
有人可以解释为什么它将日期时间值转换为美国格式而不是英国的默认值吗?我再次运行这个显式设置日期格式为ymd然后它正常工作???任何人的想法?
select *
from sys.syslanguages
where Name = @@LANGUAGE
以Trassposed格式输出上述查询以便更好地查看。
+-------------+------------------------------------------------------------+
| langid | 23 |
| dateformat | dmy |
| datefirst | 1 |
| upgrade | 0 |
| name | British |
| alias | British English |
| months | January,February,March,April,May,June,July, |
| | August,September,October,November,December |
| shortmonths | Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec |
| days | Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday |
| lcid | 2057 |
| msglangid | 1033 |
+-------------+------------------------------------------------------------+
答案 0 :(得分:0)
尝试YYYMMDD
select
a = datename(M,'20160204')
, b = datename(M,'20160204 14:42:26')
, c= datename(M,Cast('20160204' as Date))
, d = datename(M,CAST('20160204 14:42:26' as DateTime))
, e = Cast('20160204' as Date)
, f = CAST('20160204 14:42:26' as DateTime)
, g = CAST('20160204 14:42:26' as SmallDateTime)
, h = CONVERT(DateTime,'20160204 14:42:26')
这是SQL Server中所有日期样式中最安全的。 YYYY-DD-MM确实存在(darn it),它可能会因为YYYY-MM-DD而感到困惑
另一件事是使用CONVERT(datatype,value,style_number),如果包括stye数,例如convert(date,'2016-02-04 04:05:06.007',121)然后转换知道YYYY MM DD日期部分的顺序。