SQL查询在两个日期之间选择错误

时间:2013-02-25 23:12:03

标签: sql sql-server sql-server-2008

我正在努力处理SQL中的查询,因此需要您的帮助。此查询未提供我想要的确切结果。我需要提取两个日期之间的所有日期。

我尝试了两个问题:

SELECT a.MemberID,CONVERT(varchar(12), b.BirthDate, 101) AS BirthDate
FROM Members_Hired AS a
    INNER JOIN Members AS b
        ON a.ReferenceID = b.RecordID
WHERE (CONVERT(varchar(12), b.BirthDate, 101) >= '02/01/2013'
    and CONVERT(varchar(12), b.BirthDate, 101) <= '02/27/2013')

SELECT a.MemberID,CONVERT(varchar(12), b.BirthDate, 101) AS BirthDate
FROM Members_Hired AS a
    INNER JOIN Members AS b
        ON a.ReferenceID = b.RecordID
WHERE (CONVERT(varchar(12), b.BirthDate, 101) BETWEEN '02/01/2013' and '02/27/2013')

这会给出日期为'02/05/1990''02/17/1990'的结果。它只考虑月份和日期,而不仅仅是年份。

2 个答案:

答案 0 :(得分:2)

我认为你正在比较字符串而不是日期时间,所以结果有记录&#39; 02/25&#39; &安培; &#39; 02/17#39;

答案 1 :(得分:1)

假设您的生日字段是DateTime类型,您需要将输入转换为相同类型。

你试过吗?

WHERE (b.BirthDate BETWEEN Cast('02/01/2013' As DateTime) and Cast('02/27/2013' As DateTime))