2016-11-24 76 views
2

下午,个月从日期返回不正确的值

我有一个SQL服务器的问题,我可以做一些帮助。 当我在错误的日期范围内返回行的日期范围中运行select语句时。

例如如果我执行以下

select * from theTable where startDate between '2016-09-01 00:00:00' and '2016-09-08 23:59:59' 

我希望排在startDate是1日和9月8日之间,有什么我却越来越是1月9日和8月9日之间的startDate行。

我检查我有使用DATEBASE设置的语言:

select * from sys.syslanguages order by name where name = @@language 

这将返回英国

DBCC USEROPTIONS回报

textsize    2147483647 
language    British 
dateformat   dmy 
datefirst   1 
lock_timeout   -1 
quoted_identifier SET 
arithabort   SET 
ansi_null_dflt_on SET 
ansi_warnings  SET 
ansi_padding   SET 
ansi_nulls   SET 
concat_null_yields_null SET 
isolation level   read committed 

我已经检查了默认语言登录,这也是英国人。

当我执行print month('2016-09-01 00:00:00')

它返回1,而不是9.除非是我弄错了日期和时间上面应该是ODBC规范yyyy-mm-dd hh:mi:ss(24h)

为什么打印1而不是9,更重要的是我该如何解决?

印刷@@version返回

Microsoft SQL Server 2005 - 9.00.5057.00 (X64) 
    Mar 25 2011 13:33:31 
    Copyright (c) 1988-2005 Microsoft Corporation 
    Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2) 

谢谢您的帮助。 如果这个问题已经得到解答,你可以指点一下,但我找不到答案。

+2

使用明确的格式('YYYYMMDD'):'where startDate> ='20160901'and startDate <'20160909'' – Lamak

回答

2

您似乎有一个相对不寻常的国际化设置,其中默认值是YDM而不是YMD。

您可以随时使用日期没有连字符:

select * 
from theTable 
where startDate >= '20160901' and 
     startDate < '20160909'; 

这些总是在SQL Server解释为YYYYMMDD。

+0

确实。以法语为例,选择2016年1月9日的“2016-09-01 00:00:00”。 –

-1

如果您想时间戳还要在评估被认为是你的WHERE条件,尝试转换日期为:

CONVERT(datetime,'2016-09-01 00:00:00',101) 

,所以你的查询会变成:

select * from theTable 
where startDate between 
CONVERT(datetime,'2016-09-01 00:00:00',101) 
and 
CONVERT(datetime,'2016-09-08 23:59:59',101) 

你一个月这样将[9]而不是[1],并且时间戳也将被考虑。

相关问题