May 21, 2008 at 5:56 pm
I have a Stored Procedure and a table with a date column in it. I am filtering on the date column with a WHERE clause in a SELECT statement. I also have 1 parameter that is a datetime type. The value in the parameter may have a valid date in it, but sometimes the value maybe empty.
When the parameter is empty, how do I write the T-SQL to tell the WHERE clause to get all dates? For example:
SELECT OrigBondDate
FROM BondTable
WHERE
convert(smalldatetime,OrigBondDate) = @BondDate
This works great if there is a date in the parameter, but what if there is no date? If there is no date in the parameter, can T-SQL tell the server to get all dates in the column?
Thanks.
May 21, 2008 at 8:30 pm
First, the CONVERT on the datetime column will kill any chance of using an Index SEEK if the column is indexed. Second, you just need to add a simple condition to achieve what you want... both are combined in the following code...
SELECT OrigBondDate
FROM BondTable
WHERE ( OrigBondDate >= @BondDate
AND OrigBondDate < @BondDate +1)
OR @BondDate IS NULL
Of course, @BondDate should be a DateTime variable...
--Jeff Moden
Change is inevitable... Change for the better is not.
May 21, 2008 at 10:37 pm
Thanks, that did it.
May 21, 2008 at 11:33 pm
My pleasure. Thank you for the feedback.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply