I am using below SQL query to get data by mentioning date range without year.
Select * from table where Left(Convert(Varchar(10),Cast(createddate As Date),101),5) between '11/01' and '12/31'
The above query works say when the user enter the date range as '11/01' to '12/31'. But, when the user enters anything like '11/01' to '01/31' or '05/31' to 02/28' etc, the query is not returning any data.
Is it possible to make it work for above ranges?
答案 0 :(得分:1)
我会使用month()
函数:
Select *
from table
where month(nm_birthdate) in (11, 12);
但是,您的查询应该有效,因为101个零垫日和月。
如果您想以MM / DD格式查找两个日期之间的生日,您可以这样做:
where (@startmmdd < @endmmdd) and convert(varchar(5), nm_birthdate, 101) between @startmmdd and @endmmdd) or
(@startmmdd > @endmmdd) and convert(varchar(5), nm_birthdate, 101) not between @endmmdd and @startmmdd)
根据您是否要包含终点,可能会进行一些调整。
注意:
@startmmdd
和@endmmdd
需要采用MM / DD格式。数小时和数小于10的前导零需要。left()
。答案 1 :(得分:0)
使用DATEPART,如下所示:
SELECT * FROM table WHERE datepart(month, birthdate) IN (11, 12)
当然,您可以将其与:
结合使用 datepart(day, birthdate)
为了获得更复杂的条件。 希望它有所帮助