This isn\'t about checking if a record exists before selecting it, or viceversa.
The issue is this, I have a database with many records, they are stored by date, by
Eric Fan had the right idea, but I thought it might help to see an implementation:
Here's a function that will return a table of the inclusive dates:
CREATE FUNCTION dbo.fDatesBetween(@startDate Date, @endDate Date)
RETURNS @tbl TABLE
(
a_date Date
)
AS BEGIN
DECLARE @thisDt Date
SET @thisDt = @startDate
WHILE @thisDt <= @endDate
BEGIN
INSERT INTO @tbl SELECT @thisDt
SET @thisDt = DateAdd(day, 1, @thisDt)
END
RETURN
END
Now, if you do an outer join to your table from the function results, you will have what you are looking for:
SELECT DATES.a_date, SampleTable.value1, SampleTable.value2
FROM dbo.fDatesBetween(@startDate, @endDate) DATES
LEFT JOIN SampleTable
ON DATES.a_date = SampleTable.dt
That should give you just what you asked for.