在SQL Server中比较日期字符串和日期时间? [英] Compare a date string to datetime in SQL Server?

查看:874
本文介绍了在SQL Server中比较日期字符串和日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL Server中,我有一个 DATETIME 列,其中包含一个时间元素。

In SQL Server I have a DATETIME column which includes a time element.

示例:

'14 AUG 2008 14:23:019'

最好方法是什么,只选择某一天的记录,忽略时间部分?

What is the best method to only select the records for a particular day, ignoring the time part?

示例:(不安全,因为它不匹配时间部分并且不返回任何行)

Example: (Not safe, as it does not match the time part and returns no rows)

DECLARE  @p_date DATETIME
SET      @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

SELECT *
FROM   table1
WHERE  column_datetime = @p_date

注意:由于这个网站也是记下笔记和技巧你拿起然后忘记,发布我自己的答案这个问题作为DATETIME MSSQL的东西可能是我查找最多的主题在SQLBOL中的主题。

更新更清楚的例子更具体。

Update Clarified example to be more specific.

strong>对不起,但是我不得不修改错误的答案(答案返回错误的结果)。

Edit Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).

@Jorrit: WHERE ;'20080813'AND date <'20080815')将返回第13和14日。

@Jorrit: WHERE (date>'20080813' AND date<'20080815') will return the 13th and the 14th.

@wearejimbo:没有雪茄!徽章。您错过了在14/08/2008 23:59:001至23:59:999(即午夜前不到1秒钟)写的记录。

@wearejimbo: Close, but no cigar! badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.)

推荐答案

技巧1:

 DECLARE @p_date DATETIME
 SET     @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

 SELECT  *
 FROM    table1
 WHERE   column_datetime >= @p_date
 AND     column_datetime < DATEADD(d, 1, @p_date)

这样做的好处是, 'column_datetime'(如果存在)。

The advantage of this is that it will use any index on 'column_datetime' if it exists.

这篇关于在SQL Server中比较日期字符串和日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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