[英]How to use Where clause with datetime in SQL Server 2008
I have written this query: 我写了这个查询:
SELECT *
FROM w_tbl
WHERE DID NOT IN (SELECT DId FROM tbl_Assign)
AND CAST(MeasDateTime AS Date) = @dta
ORDER BY
CAST(MeasDateTime as DATE) DESC
So as you can see I am sending a parametrized query. 如您所见,我正在发送参数化查询。
So I put 24/09/2010 00:00:00
for @dta
所以我把
@dta
放在24/09/2010 00:00:00
But I get this error: 但是我得到这个错误:
Conversion failed when converting date and/or time from charterer string.
从承租人字符串转换日期和/或时间时,转换失败。
I tell you why I am doing this and my purpose: 我告诉你我为什么这样做和我的目的:
I have a datetime column, and I want to select/fetch all data by date only (ie I don't want to fetch datetime wise, it has to be just according to date) 我有一个datetime列,并且我只想按日期选择/获取所有数据(即,我不想明智地获取datetime,它只能根据日期)
If you want to select by date only and you have DateTime type, use date functions: 如果只想按日期选择并且具有DateTime类型,请使用日期函数:
DATEADD ( dd , 0 , DATEDIFF ( dd , 0 , @dta))
So in your case: 因此,在您的情况下:
SELECT *
FROM w_tbl
WHERE DID NOT IN (SELECT DId FROM tbl_Assign)
AND DATEADD ( dd , 0 , DATEDIFF ( dd , 0 , MeasDateTime)) = DATEADD ( dd , 0 , DATEDIFF ( dd , 0 , @dta))
ORDER BY
MeasDateTime DESC -- No need for CAST/CONVERT here, it will be ok either way
First check @dta value cause 24/09/2010 may be wrong date. 第一次检查@dta值原因24/09/2010可能是错误的日期。 Try using 09/24/2010 or 24-Sep-2010 and check.
尝试使用2010年9月24日或2010年9月24日进行检查。 Always to
avoid confusion in dd/MM/yyyy and MM/dd/yyyy
use MMM for month. 始终
avoid confusion in dd/MM/yyyy and MM/dd/yyyy
使用月份的MMM。 SQL handles datetime format with MMM correctly. SQL使用MMM正确处理日期时间格式。 Like dd-MMM-yyyy.
就像dd-MMM-yyyy。 By default SQL uses US standards and take date is format MM/dd/yyyy.
默认情况下,SQL使用美国标准,日期格式为MM / dd / yyyy。
Thanks. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.