Discussion Locked

Comparision of Dates in SQL Server

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I gave a query where there was comparison operator used with datetime. If i gave a Date in 'MDY' format output is as expected , but with 'DMY' format same query is yielding undesirable output.
Query is as Follows
-- MDY
SELECT * FROM CALL_DETAILS
WHERE convert (varchar,cal_opn_dt_time,101) < '05/22/2001'

--DMY
SELECT * FROM CALL_DETAILS
WHERE convert (varchar,cal_opn_dt_time,103) < '22/05/2001'

Please tell me solution for the same as I wanna use this query for 2 Formats 'MDY' and 'DMY'in Procedure.

'Sanjeev'

1 reply

by steved

The best way to compare dates is using datetime data types, not strings. If you want to use strings, you'll have to rearrange them into year-month-day order.

When converting to datetime data types, you can use the SET DATEFORMAT function to specify what order you want to use in your strings. So here's one way to accomplish your objective:

-- MDY
SET DATEFORMAT mdy
DECLARE @datevar datetime
SET @datevar = '05/22/2001'
SELECT * FROM CALL_DETAILS
WHERE cal_opn_dt_time < @datevar

--DMY
SET DATEFORMAT dmy
DECLARE @datevar datetime
SET @datevar = '22/05/2001'
SELECT * FROM CALL_DETAILS
WHERE cal_opn_dt_time < @datevar

I hope this helps.

Steve Diamond

This discussion is closed to new replies.