0

I have the following code which allows using a variable within an IN clause:

    DECLARE @Ids varchar(50);
    SET @Ids = '24,25';

    SELECT * 
    FROM table
    WHERE ','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),id_field)+',%';

Since @Ids is an optional field which can be null, how would I modify the code such that it incorporates

    (@Ids IS NULL OR id_field = @Ids)
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

1 Answers1

1

Pretty much what you already have (parenthesis added for readability)

WHERE (@Ids IS NULL) OR (','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),id_field)+',%')

On a side note do realize that a query like this circumvents any index on id_field that might exist and will do a table scan to find matches.

Igor
  • 60,821
  • 10
  • 100
  • 175