DJDMorrison
DJDMorrison

Reputation: 1327

Using Wildcards in SQL Where statement

I've got the following code:

SELECT ItemName 
FROM skuDetails 
WHERE skuDetails.SkuNumber = '" & search & "' 
      OR 
      skuDetails.ItemName = '%' + @search + '%'"

Basically I've got a database of items and each item has a "SKU number" which is a unique number for each item. In VB.NET I have a form where you type in either the SKU number or the name of the item into a text box and then press enter to search the database for that number or a similar name to the one you searched.

The "search" variable in the code above is the text in the textbox which the user searches.

The first WHERE statement works but the second after the OR doesn't. I expect it's something to do with how I've used the wildcard. Is there anything wrong with that statement?

Thanks in advance!

Upvotes: 3

Views: 2557

Answers (2)

sll
sll

Reputation: 62504

You should use LIKE rather than equals operator in order to use pattern matching:

OR skuDetails.ItemName LIKE  '%' ...

MSDN: Pattern Matching in Search Conditions

The LIKE keyword searches for character string, date, or time values that match a specified pattern. For more information, see Data Types (Transact-SQL). The LIKE keyword uses a regular expression to contain the pattern that the values are matched against. The pattern contains the character string to search for, which can contain any combination of four wildcards

Upvotes: 4

Andrew
Andrew

Reputation: 27294

To use a wildcard, you have to say LIKE '%' + @search + '%'

Be careful though, you are opening yourself up to SQL Injection attacks with this kind of code.

Upvotes: 4

Related Questions