0

我正在尝试比较日期,但我的查询没有返回任何结果。好奇我是否正确编写了查询?

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)

这个日期比较查询有什么问题吗?

表结构如下:

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

在表 B,Minage 中,每行的 maxage 标准都会发生变化。所以范围可以是 minage 0 max age 20, minage 50 maxage 60 等等(虽然范围不重叠)。

关于查询中可能有什么问题的任何想法?

我只需要比较/计算日期而不是小时或分钟。

4

3 回答 3

1

不要将您的转换datestring. 这样做可能会导致按字符串和按日期进行的无效比较。

... WHERE a.BirthDate between b.minage and b.maxage
于 2012-09-18T16:32:04.603 回答
1

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)

于 2012-09-18T16:32:36.133 回答
-1

可能是我傻了。

看起来我不得不颠倒 minage 和 maxage 的顺序。

所以下面的查询有效:

SELECT *
FROM a, b
WHERE CONVERT(varchar(50),a.BirthDate, 101) 在 CONVERT(varchar(50),b.maxage, 101) 和 CONVERT(varchar(50),b.minage, 101) 之间

于 2012-09-18T16:40:41.407 回答