SQL LIKE使用不同的通配符模式

时间:2016-02-15 07:31:24

标签: sql-server wildcard sql-like

我有一个表单来获取用户输入。在“名称”文本框字段中,用户将指定他希望WILD Card实现的方式。例如,如果他键入abc查询应该是:

Select * from Student where Name Like '%' '@Name' + '%'

如果他键入abc**应该告诉查询返回名称从abc开始的行

Select * from Student where Name Like '@Name' + '%'

如果他输入*abc*应该告诉查询返回名称以abc结尾的行

Select * from Student where Name Like '%' + '@Name'

如何编写可以处理此类用户输入的查询? Regex会帮忙吗?

3 个答案:

答案 0 :(得分:1)

您应该尝试以下内容,

DECLARE @Name AS VARCHAR(100)='*kklik'

IF(CHARINDEX('*', @Name) = 1)
BEGIN
    Select * from Student where Name Like '@Name' + '%'
END
ELSE IF(CHARINDEX('*', @Name) >= 1)
BEGIN
    Select * from Student where Name Like '@Name' + '%'
END

答案 1 :(得分:0)

Declare @sqlText varchar(max)= "Select * from Student where Name Like '" + Replace(userinputtext, "*", "%") + "'";
Exec(@sqlText)

答案 2 :(得分:0)

试试这个

DECLARE @Name AS VARCHAR(100)='abc*'

if (CHARINDEX('*', @Name)>1)
  set @Name=Replace(@Name, '*', '%')
else 
  set @Name='%'+@Name+'%'

Declare @sqlText varchar(max)= "Select * from Student where Name Like '" + Replace(userinputtext, "*", "%") + "'";
Exec(@sqlText)