Well, As Aaron Bertrand commented, your current query can be written simply like this:
DECLARE @Desc VARCHAR(200) = ''
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE '%'+ @Desc +'%'
Since if @Desc
contains an empty string, it will result with [Desc] LIKE '%%'
-so all records where [Desc]
is not null will be returned anyway.
If @Desc
can be passed as null
, use Coalesce
to convert null
to an empty string:
...WHERE [Desc] LIKE '%'+ COALESCE(@Desc, '') +'%'
Please note that in both questions, records where the Desc
column contains null
will not be returned. If that is a nullable column and you want to also return the records where it's null
and the @Desc
parameter is also null or empty, then you should use OR
:
SELECT [id],
[Desc],
[Col1],
[Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE '%'+ @Desc +'%'
OR (COALESCE(@Desc, '') = '' AND [Desc] IS NULL)
Also, please note that this is only because of your use of LIKE
- Should you try to evaluate conditions using a different operator (such as =
, <
, >
etc') you should use the OR
syntax like in the other answers.