Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 476
DJDMorrison Avatar asked Dec 10 '25 19:12

DJDMorrison


2 Answers

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

like image 95
sll Avatar answered Dec 12 '25 10:12

sll


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.

like image 25
Andrew Avatar answered Dec 12 '25 09:12

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!