Wildcard as parameter of stored procedure

Andrew Vershinin picture Andrew Vershinin · Mar 2, 2014 · Viewed 9.1k times · Source

Suppose, I have a stored procedure, that accepts one parameter - id, and returns some data corresponding to this id. What if I want to retrieve all such data, like using wildcard in SELECT query? How to do this?

Answer

user3358344 picture user3358344 · Mar 2, 2014

You can add a trailing '%' to your query. Assume that @param is the parameter to your stored procedure:

declare @param2 varchar(100)
set @param2 = @param + '%'

select * from table where column like @param2

That will return a wildcard search beginning with the value in @param. For partial match use '%' + @param + '%'

[Edit]

Based on the below clarification in the comments:

if @id != '*' 
begin
    select * from table where column = @id
end
else
begin
    select * from table
end