The most suitable option that does not use dynamic SQL is to use an IF statement and two queries:
IF LEN(@Title) > 0 SELECT r.* FROM RECORDS r WHERE r.title LIKE '%'+ @Title +'%' ELSE SELECT r.* FROM RECORDS r
The dynamic SQL version of SQL Server 2005+ will resemble:
DECLARE @SQL NVARCHAR(4000) SET @SQL = 'SELECT r.* FROM RECORDS r WHERE 1 = 1' --will be optimized out, easier to add clauses SET @SQL = @SQL + CASE LEN(@Title) WHEN 0 THEN '' ELSE ' AND r.name LIKE ''%''+ @Title +''%'' ' END BEGIN EXEC sp_executesql @SQL, N'@Title VARCHAR(#)', @Title END
Unlike EXEC , sp_executesql will cache the query plan. You can read about it in Blessing and Curse of Dynamic SQL .
source share