views:

235

answers:

4

I'm having a problem with some T-SQL in a SP on SQLServer 2005 comparing dates. I'm running the stored procedure from c# with ADO.Net and passing a the native c# datetime datatype(could this be my issues as I know the ranges are slightly different). I do the following to compare 2 DateTime values in my SP.

CREATE PROCEDURE [dbo].[spGetLikelyMatchedIndividuals_v1]
    @ID BIGINT = NULL,
    @DOB DATETIME = NULL, ...

WHERE ISNULL(CONVERT(CHAR(8),Ind.[DateOfBirth],112),'') = ISNULL(CONVERT(CHAR(8),@DOB,112),'')

This works fine in most cases but from some reason will fail with some Datetime. This is one datetime value that fails:

1925-07-04

Does anyone have anyidea why this may fail? Also what is the best way to compare two date values without the time component?

A: 

You just want to compare the date component? You could compare

FLOOR(CAST(x.[SomeDate] as float)) = FLOOR(CAST(@SomeDate as float))

A lot less string work, and should do the job. Even better; create a 1-day range and use that...

DECLARE @from datetime, @to datetime

SET @from = CAST(FLOOR(CAST(@SomeDate as float)) as datetime)
SET @to = DATEADD(day, 1, @from)

...
WHERE x.[SomeDate] >= @from AND x.[SomeDate] < @to
Marc Gravell
and some null handling, of course...
Marc Gravell
+1  A: 

If you're comparing dates on SQL-Server, investigate the DateDiff function.

You can compare two dates quite easily and specify the granularity, eg. to the nearest day or hour or minute or whatever.

In your example, one of your values is a datetime, so convert the other to that type using the Convert function.

dave
+2  A: 

Better yet, don't do any logic against the table as this will prevent your index from being used.

Let your front end app handle the ensuring that the @DOB variable is in the correct format.

mrdenny
+1 - I think your spot on here unfourtantly the data im working with in the database has the time portion all over the place:-(
StarSignLeo
That can be worked around. "WHERE BirthDate BETWEEN CAST(CONVERT(VARCHAR(10), @DOB, 101) AS DATETIME) AND DATEADD(dd, 1, CAST(CONVERT(VARCHAR(10), @DOB, 101) AS DATETIME))"
mrdenny
+1  A: 

Seems like your date compare is correct. It may be other logic that is causing this issue. Perhaps you should paste in more of your stored procedure to find the likely problem.

Russell
It turns out your correct it was loging in my stored procedure that was excluding the results and the query was returning a valid date. Sorry for wasting everyones time.
StarSignLeo