Several viable options:
You can set @FromDate and @ToDate to the earliest or very latest date, respectively, they are NULL.
You can use sp_executesql and build a dynamic w / parameters query string as needed, for example.
DECLARE @Sql NVARCHAR(MAX) = 'SELECT * FROM CallList C WHERE 1 = 1 ' IF @FromDate IS NOT NULL BEGIN SET @Sql += ' AND C.CallDate > @xFromDate' END IF @ToDate IS NOT NULL BEGIN SET @Sql += ' AND C.CallDate < @xToDate' END EXEC sp_executesql @Sql, N'@xFromDate DATETIME, @xToDate DATETIME', @xFromDate = @FromDate, @xToDate = @ToDate
This latter approach works better than using ORs everywhere, since queries that include ORs invariably end up being optimized very poorly - they may work well for a specific set of parameters, but usually are not suitable for the same size.
source share