简体   繁体   中英

Write sql query to search using wildcard

I have a database that the user needs to search using wildcards. For example, the column Order number the user would need search by tickets starting with 3011* or 201*. Since the ticket number has many different numbers it would need to be build by parameter. I know I have to use LIKE and I know how to write the query with LIKE if the search would start with the same number all the time, but I do not know how to write it using a parameter for user input.

For example:

ITEM                ORDER_NO
Chair Order         3011134
Table Order         A230445
Tile Order          1032234

So when the user inputs a search for orders starting with *3011 the Chair order would pop up.

I know how to search for exact match but not for wildcards

I have done some research on this, but nothing on using a parameter. Any help or guidance will be appreciated.

Have a look at the following : SQL Wildcards

Usually in SQL you will do things like :

declare @Search varchar(20);
set @Search = '3011';

select * 
from TableName
where FieldName like '%' + @Search + '%';

This allows you to search for things staring with, ending with and having the search text in the middle of the field you are looking at.

Just be careful for SQL Injections.(Alwasy validate user inputs.)

SELECT item, order_no
FROM 'your table'
WHERE order_no
LIKE '3011%'

The % wildcard symbol with LIKE will return all rows where the order_no starts with 3011 - so from your table the above query would return Chair Order - 3011134

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM