Here as a version that uses sp_executesql
parameters and so is not vulnerable to SQL injection - it should also provide better performance, to quote MSDN:
Because the Transact-SQL statement itself remains constant and only
the parameter values change, the SQL Server query optimizer is likely
to reuse the execution plan it generates for the first execution.
CREATE PROCEDURE [dbo].[Yourproc]
(
@Search NVARCHAR(100) = N''
)
AS
DECLARE @LargeComplexQuery NVARCHAR(MAX) = 'SELECT * from People WHERE Name LIKE ''%'' + COALESCE(@Search, '''') + ''%'' ORDER BY Name'
EXEC sys.sp_executesql @LargeComplexQuery, N'@Search NVARCHAR(100)', @Search = @Search
I've made some assumptions, such as if you pass empty string or NULL as a search condition then you get all people returned.
Testing it out - dummy schema & data:
CREATE TABLE People(Name NVARCHAR(MAX))
INSERT INTO People(Name)
VALUES ('Mr Smith'), ('Mrs Jones'), ('Miss O'' Jones')
Testing stored proc execution:
DECLARE @search NVARCHAR(100) = N'Jones';
EXEC YourProc @Search; --Should get back both Mrs Jones and Miss O'Jones
SET @search = N'O'' Jones';
EXEC YourProc @Search; --Should get back just Miss O'Jones
SET @search = N'';
EXEC YourProc @Search; --Should get everyone, same as if you passed no search value at all
SET @search = NULL
EXEC YourProc @Search; --Should get everyone
MSDN Documentation on sp_executesql