Yes they will be used (well probably, check the execution plan - but I do know that the optional-ness of your parameters shouldn't make any difference)
If you are having performance problems with your query then it might be a result of parameter sniffing. Try the following variation of your stored procedure and see if it makes any difference:
CREATE PROCEDURE dbo.GetActiveEmployee
@startTime DATETIME=NULL,
@endTime DATETIME=NULL
AS
SET NOCOUNT ON
DECLARE @startTimeCopy DATETIME
DECLARE @endTimeCopy DATETIME
set @startTimeCopy = @startTime
set @endTimeCopy = @endTime
SELECT columns
FROM table
WHERE (@startTimeCopy is NULL or table.StartTime >= @startTimeCopy) AND
(@endTimeCopy is NULL or table.EndTime <= @endTimeCopy)
This disables parameter sniffing (SQL server using the actual values passed to the SP to optimise it) - In the past I've fixed some weird performance issues doing this - I still can't satisfactorily explain why however.
Another thing that you might want to try is splitting your query into several different statements depending on the NULL-ness of your parameters:
IF @startTime is NULL
BEGIN
IF @endTime IS NULL
SELECT columns FROM table
ELSE
SELECT columns FROM table WHERE table.EndTime <= @endTime
END
ELSE
IF @endTime IS NULL
SELECT columns FROM table WHERE table.StartTime >= @startTime
ELSE
SELECT columns FROM table WHERE table.StartTime >= @startTime AND table.EndTime <= @endTime
BEGIN
This is messy, but might be worth a try if you are having problems - the reason it helps is because SQL server can only have a single execution plan per sql statement, however your statement can potentially return vastly different result sets.
For example, if you pass in NULL and NULL you will return the entire table and the most optimal execution plan, however if you pass in a small range of dates it is more likely that a row lookup will be the most optimal execution plan.
With this query as a single statement SQL server is forced to choose between these two options, and so the query plan is likely to be sub-optimal in certain situations. By splitting the query into several statements however SQL server can have a different execution plan in each case.
(You could also use the exec
function / dynamic SQL to achieve the same thing if you preferred)