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.)
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.
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".
We can compare dates using Comparison Operators in SQL like, = (Equals), < (Less than), > (Greater than), <= (Less than Equal), >= (Greater than Equal), <> (Not Equal), etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With