Right now I have something like:
CREATE PROCEDURE [dbo].[sp_GetFilteredInformation]
@pItem nvarchar(max) = NULL,
@pCity nvarchar(max) = NULL,
@pSerialN nvarchar(max) = NULL,
@pPromise datetime = NULL,
@pSalesOrder nvarchar(max) = NULL,
@pLineNumber int = NULL
DECLARE @vQuery nvarchar(max)
IF (@pItem IS NOT NULL)
BEGIN
SET @vQuery += 'AND ITEM LIKE '' + @pItem + '''
END
IF (@pCity IS NOT NULL)
BEGIN
SET @vQuery += 'AND CITY LIKE '' + @pCity + '''
END
... and so on, so in the end I'll have
SELECT *
FROM TABLE
WHERE 1 = 1 + @vQuery
I think this is going to work, but it doesn't seems efficient to me. Is there a way to optimize this process and filter information with multiple parameters, with the option of some of them being null?
sp_executesql, do not inject themsp_prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoidsp_and use something else as a prefix - or no prefix at all!sp_prefix is also a problem and should not be used.