I have this sql stored procedure which is supposed to look at a particular table and return job numbers based on a date column. This works great except for when its run Saturday morning (and should return all job numbers with a date of Friday, but returns no rows). Any suggestions? Is there some logic problem here I'm not seeing? How might I track this down?
Stored Procedure
ALTER Procedure [dbo].[JC_GetJobsClosedYesterday]
As
SELECT [JobNumber]
FROM [NCLGS].[dbo].[JobClosedDate]
Where LastInvoiceDate between dbo.ufn_StartOfDay (DATEADD(d, -1, GETDATE())) AND dbo.ufn_StartOfDay (GETDATE())
order by JobNumber desc
And the start of day function.
ALTER function [dbo].[ufn_StartOfDay] ( @inDate datetime )
RETURNS DateTime AS
BEGIN
DECLARE @Now datetime
set @Now = @inDate
DECLARE @DayStart datetime
set @DayStart = @Now
set @DayStart = DATEADD (ms, -DATEPART(ms,@Now),@DayStart)
set @DayStart = DATEADD (s, -DATEPART(s,@Now),@DayStart)
set @DayStart = DATEADD (mi, -DATEPART(mi,@Now),@DayStart)
set @DayStart = DATEADD (hh, -DATEPART(hh,@Now),@DayStart)
return @DayStart
END
EDIT: I'm not having trouble with my date conversion (unless it doesn't know how to handle Fridays). I need help with the returning no rows part.
SAMPLE DATA:
JobNumber LastInvoiceDate DayOfWeek
112117 2011-06-13 00:00:00.000 Monday
112089 2011-06-10 00:00:00.000 Friday
112090 2011-06-10 00:00:00.000 Friday
112068 2011-06-10 00:00:00.000 Friday
112082 2011-06-10 00:00:00.000 Friday
UPDATE: Now I'm really confused. This "no data on fridays" thing has been happening (happened again last friday), but I still can't figure it out. Is it possible that GETDATE() isn't returning what I think its returning? Because when I try the following modifications based on @Thomas's suggestion, both methods get data, but the report that generated based on this code last sat has no data.
DECLARE @date datetime
--SET @date = '2011-06-21 13:42:27.257'
SET @date = '2011-06-11 03:42:27.257'
--Original Code
SELECT [JobNumber]
FROM [NCLGS].[dbo].[JobClosedDate]
Where LastInvoiceDate between dbo.ufn_StartOfDay (DATEADD(d, -1, @date)) AND dbo.ufn_StartOfDay (@date)
order by JobNumber desc
--Returns 21 records
--Modified based on @Thomas suggestion
Select [JobNumber]
From [NCLGS].[dbo].[JobClosedDate]
Where LastInvoiceDate >= DateAdd( d, DateDiff( d, 0, @date ) - 1, 0 )
And LastInvoiceDate < DateAdd( d, DateDiff( d, 0, @date ), 0 )
Order By JobNumber Desc
--Returns 21 records