Sql server SQL Server-在名字和姓氏字段中搜索全名
我假设我的用户输入可以是三种格式之一:“John”、“John Doe”或“Doe”Sql server SQL Server-在名字和姓氏字段中搜索全名,sql-server,tsql,full-text-search,Sql Server,Tsql,Full Text Search,我假设我的用户输入可以是三种格式之一:“John”、“John Doe”或“Doe” 我们最新版本的SQL Server数据库表Persons有FirstName和LastName列。我真的不知道用户是否输入了全名、姓氏或名字作为输入,搜索并返回可能匹配的记录的最佳方法是什么?我正在考虑进行全文搜索,但不确定这两列的搜索结果如何,尤其是当搜索“John Doe”时,每列只能包含部分输入。我将分离输入,并在应用程序层上显式显示它们。如果这不是一个选项,那么一种方法(如果名字与姓氏相同,则会出现误报
我们最新版本的SQL Server数据库表Persons有FirstName和LastName列。我真的不知道用户是否输入了全名、姓氏或名字作为输入,搜索并返回可能匹配的记录的最佳方法是什么?我正在考虑进行全文搜索,但不确定这两列的搜索结果如何,尤其是当搜索“John Doe”时,每列只能包含部分输入。我将分离输入,并在应用程序层上显式显示它们。如果这不是一个选项,那么一种方法(如果名字与姓氏相同,则会出现误报)将类似于下面的代码段。这假设只有一个空间(如果有的话),并且基于许多假设,这些假设将根据用户输入的内容而改变,因此我建议在应用层处理这个问题
declare @input varchar(256) = 'John Doe'
--if there is no space, then only a FirstName or LastName was supplied
if (select charindex(' ',@input)) = 0
begin
select
*
from
YourTable
where
FirstName = @input
or
LastName = @input
end
--if a space was found in input, we assume it was a FullName
else
begin
select
*
from
YourTable
where
FirstName = left(@input,charindex(' ',@input))
and
LastName = ltrim(right(@input,len(@input) - charindex(' ',@input)))
end
更模糊的方法是使用LIKE
子句
select
*
from
YourTable
where
FirstName + ' ' + LastName like + '%' + @input + '%'
从表中选择*(FirstName+LastName),如“%input%”对于这种情况,我更喜欢向表中添加一个CleanName列。在您的实例中,这将是“名字”和“姓氏”列合并为一个列,并删除所有非字母数字字符,因此John Doe将是CleanName列中的johndoe。这是添加/更新数据查询的一部分
Use the variable with datatype table or Use temporary table,here i use temporary table,check this its working
declare @input_name varchar(100)
create table #name(name1 nvarchar(50),name2 nvarchar(50))
set @input_name = 'John'----('John', 'John Doe', 'Doe')
INSERT INTO #name SELECT substring(@input_name, 1,charindex(' ',@input_name)) ,substring(@input_name, charindex(' ',@input_name),len(@input_name)-charindex(' ',@input_name)+1)
select * from #name
select * from Persons where FirstName =(select name1 from #name ) or LastName =(select name2 from #name ) or FirstName =(select name2 from #name ) or LastName =(select name1 from #name )
drop table #name
然后,您可以执行一个简单的查询来查找匹配项
我更喜欢这种方法,因为有些姓氏有非字母数字字符,例如O'Reilly,这样就不需要用户完全准确地拼写和格式。如果我理解正确,以您给出的John Doe示例为例,可能是(FirstName,LastName):
NULL,Doe
或John,Doe
或约翰,空
?。