我有一个表单来获取用户输入。在“名称”文本框字段中,用户将指定他希望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
会帮忙吗?
答案 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)