View Single Post

   
  #6 (permalink)  
Old 02-28-2008, 08:08 PM
louis nguyen
 
Posts: n/a
Default Re: Need help with MS SQL query

"Fred Thompson" <fredr@aol.com> wrote in message news:<DISAb.456981$HS4.3574769@attbi_s01>...
> I'm using MS SQL 2000 server. I have a table which includes a date field
> which has people's birthdays in it. How can I write a query to return all
> the records of people with birthdays within the next 30 days? (Based on
> system date as the starting point.) Actual year of birthday is irrelevant.
> Also the next 30 days may span into the next month, or the next year.

Hi Fred,

The simplest way I can think of is create a temp table with the next
30 days and join it against your birthday table on month()=month() and
day()=day(). The code would be like:

create table #T(bdays datetime)
declare @i int, @d datetime
select @d=getdate()
select @d=cast(year(@d) as varchar)
+'/'+cast(month(@d) as varchar)
+'/'+cast(day(@d) as varchar)

set @i=0
while @i<=30 begin
insert into #T
select bdays=dateadd(day,@i,@d)
set @i=@i+1
end

select a.bdays
from birthdays as a
join #T as b
on month(a.bdays)=month(b.bdays)
and day(a.bdays)=day(b.bdays)
Reply With Quote