I want to be able to pass in a list of parameters, and ignore the ones which are NULL. So that the query is in effect pretending that the filter isn\'t there and ignoring it
Thanks, This was helpful. I have decided to use the sp_ExecuteSQL method due to the potential performance advantages mentioned. I have a slightly different take on it which you may find helpful.
DECLARE @sql nvarchar(4000)
DECLARE @where nvarchar(1000) =''
SET @sql = 'SELECT * FROM MyTable'
IF @Param1 IS NOT NULL
SET @where = @where + ' AND Field1 = @Param1'
IF @Param2 IS NOT NULL
SET @where = @where + ' AND Field2 = @Param2'
IF @Param3 IS NOT NULL
SET @where = @where + ' AND Field3 = @Param3'
-- Add WHERE if where clause exists, 1=1 is included because @where begins with AND
IF @where <> ''
SET @sql = @sql + ' WHERE 1=1' + @where
--Note that we could also create order parameters and append here
SET @sql = @sql + ' ORDER BY Field1'