Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a date string to datetime in SQL Server?

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

Example:

'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 

Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.


Update Clarified example to be more specific.


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

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

@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.)

like image 808
Guy Avatar asked Aug 14 '08 09:08

Guy


People also ask

Can we compare date with string in SQL?

Date can be compared in sqlserver using string comparision: e.g. Show activity on this post. Show activity on this post. Show activity on this post.

Can we compare date with datetime in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".

How do you compare dates in SQL?

We can compare dates using Comparison Operators in SQL like, = (Equals), < (Less than), > (Greater than), <= (Less than Equal), >= (Greater than Equal), <> (Not Equal), etc.


1 Answers

Technique 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) 

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

like image 94
Guy Avatar answered Sep 20 '22 07:09

Guy