my first time posting.
I have a tricky task of finding the latest date within a range, but excluding multiple other date ranges. I have code that does work, but it seems awfully taxing.
I am selecting the MAX(Date) within a range. However, I have a table, bfShow, where each show has its own date-range (stored as DateStart and DateEnd). So I need the MAX(Date) within the range which does NOT have a show on that date (there may be 0 to 99 shows overlapping my date-range).
Note: I have dbo.fnSeqDates which works great (found via Google) and returns all dates within a range – makes for very fast filling in 6/1/12, 6/2/12, 6/3/12…6/30/12, etc.
What I’m doing (below) is creating a table with all the dates (within range) in it, then find all the Shows within that range (#ShowIDs) and iterate through those shows, one at a time, deleting all those dates (from #DateRange). Ultimately, #DateRange is left with only “empty” dates. Thus, the MAX(Date) remaining in #DateRange is my last date in the month without a show.
Again, my code below does work, but there’s got to be a better way. Thoughts?
Thank you,
Todd
CREATE procedure spLastEmptyDate
@DateStart date
, @DateEnd date
as
begin
-- VARS...
declare @ShowID int
declare @EmptyDate date
-- TEMP TABLE...
create table #DateRange(dDate date)
create table #ShowIDs(ShowID int)
-- LOAD ALL DATES IN RANGE (THIS MONTH-ISH)...
insert into #DateRange(dDate)
select SeqDate
from dbo.fnSeqDates(@DateStart, @DateEnd)
-- LOAD ALL SHOW IDs IN RANGE (THIS MONTH-IS)...
insert into #ShowIDs(ShowID)
select s.ShowID
from bfShow s
where s.DateStart = @DateStart
-- PRIME SHOW ID...
set @ShowID = 0
select @ShowID = min(ShowID)
from #ShowIDs
-- RUN THRU ALL, REMOVING DATES AS WE GO...
while (@ShowID > 0)
begin
-- REMOVE FROM TEMP...
delete DR
from #DateRange DR
, bfShow s
where DR.dDate between s.DateStart and s.DateEnd
and s.ShowID = @ShowID
-- DROP THAT ONE FROM TEMP...
delete from #ShowIDs
where ShowID = @ShowID
-- GET NEXT ID...
set @ShowID = 0
select @ShowID = min(ShowID)
from #ShowIDs
end
-- GET LAST EMPTY SPOT...
select @EmptyDate = max(dDate)
from #DateRange
-- CLEAN UP...
drop table #DateRange
drop table #ShowIDs
-- RETURN DATA...
select @EmptyDate as LastEmptyDateInRange
end
Let us know what version of SQL Server you’re on because that will help determine your options, but you should be able to use the BETWEEN operator in a JOIN between the fnSeqDates function (it’s a table-valued function, so you can join to it directly rather than inserting them into a temp table) and the bfShow tables: