views:

235

answers:

2

So I have a stored procedure that accepts a product code like 1234567890. I want to facilitate a wildcard search option for those products. (i.e. 123456*) and have it return all those products that match. What is the best way to do this?

I have in the past used something like below:

*SELECT @product_code = REPLACE(@product_code, '*', '%')

and then do a LIKE search on the product_code field, but i feel like it can be improved.

+1  A: 

What your doing already is about the best you can do.

One optimization you might try is to ensure there's an index on the columns you're allowing this on. SQL Server will still need to do a full scan for the wildcard search, but it'll be only over the specific index rather than the full table.

As always, checking the query plan before and after any changes is a great idea.

BQ
A: 

A couple of random ideas

It depends, but you might like to consider:

  • Always look for a substring by default. e.g. if the user enters "1234", you search for:

    WHERE product like "%1234%"

  • Allow users full control. i.e. simply take their input and pass it to the LIKE clause. This means that they can come up with their own custom searches. This will only be useful if your users are interested in learning.

    WHERE product like @input

AJ