简体   繁体   English

编写SQL查询以使用通配符进行搜索

[英]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*. 例如,用户需要按3011 *或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. 我知道我必须使用LIKE,并且如果搜索始终始终以相同的数字开头,那么我知道如何使用LIKE编写查询,但是我不知道如何使用用户输入的参数来编写查询。

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. 因此,当用户输入以* 3011开头的订单搜索时,会弹出主席订单。

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 看一下以下内容: SQL通配符

Usually in SQL you will do things like : 通常,在SQL中,您将执行以下操作:

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.) 请注意SQL注入。(可以验证用户输入。)

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 带有LIKE的%通配符将返回order_no以3011开头的所有行-因此从表中上述查询将返回Chair Order-3011134

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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