Domanda

I am trying to compare dates, but my query doesnot return any result. Curious if I have written the query correctly ?

SELECT *
FROM a, b               
WHERE
CONVERT(varchar(50),a.BirthDate, 101) between CONVERT(varchar(50),b.minage, 101) and CONVERT(varchar(50),b.maxage, 101)

Is there anything wrong with this date comparison query ??

Table structure is as :

Table a:
Column Name     Datatype
Birthdate       Date

Table b's row:
Column Name     Datatype
minage          Date - calculated as : select DATEADD(year, -41, GETDATE())
maxage          Date - calculated as : select DATEADD(year, -21, GETDATE())

In table B, Minage, maxage criteria changes for each row. So range can be as minage 0 max age 20, minage 50 maxage 60 etc.(range not overlapping though).

Any idea on what might be wrong in the query ?

I need to compare/calculate only with date not hours or minutes.

È stato utile?

Soluzione 3

May be stupid of me.

Looks like I had to reverse order of minage and maxage.

so the below query works:

SELECT *
FROM a, b
WHERE CONVERT(varchar(50),a.BirthDate, 101) between CONVERT(varchar(50),b.maxage, 101) and CONVERT(varchar(50),b.minage, 101)

Altri suggerimenti

Remove all the converts (to varchar)

SELECT *
FROM a, b               
WHERE
a.BirthDate between b.minage and b.maxage

if you need to remove the Time part of a DateTime you can do: CAST(a.BirthDate AS Date)

Don't convert your date to string. Doing it may cause invalid comparison by string and by date.

... WHERE a.BirthDate between b.minage and b.maxage
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top