tsql多列多搜索条件

h6my8fg2  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(366)

使用sql server 2012。
在我们的网页上,我们有多个文本框。用户可以在一个输入框中单击“搜索”或在两个输入框中单击“搜索”。。。
名字

地址行
员工代码
语言(共7个文本框)
示例t-sql:

WHERE FirstName = @FirstName

如果 @firstname 如果没有在文本框中输入,则我不希望它成为 where 条款

AND LastName = @LastName

这里相同:如果姓氏没有在文本框中输入,那么我不希望它包含在 where 条款
... 等等
问题:所有这些表都包含超过一百万行,因此由于性能影响,我不能在where子句中使用case语句
有没有其他的方法可以解决这个问题?

8aqjt8rx

8aqjt8rx1#

使用全文搜索可以得到相同的结果。那么你就不必创建动态采石场了。而且由于使用不同的服务,搜索速度非常快。
首先,您必须创建一个fulltextcatalog,然后向其中添加表和列(https://docs.microsoft.com/en-us/sql/relational-databases/search/full-text-search?view=sql-server-ver15)
我用AdventureWorksDB写了一个演示。可以根据表和列转换此代码。我刚刚在这里添加了3列,您可以将所有列添加到全文中。

USE [AdventureWorks2016]
GO

/******Object:  FullTextCatalog [SearchEmp]    Script Date: 6/24/2020 8:11:33 AM******/
CREATE FULLTEXT CATALOG [SearchEmp] WITH ACCENT_SENSITIVITY = ON
GO

**strong text**

CREATE FULLTEXT INDEX ON [Person].[Person](
[FirstName] LANGUAGE 'English', 
[LastName] LANGUAGE 'English', 
[MiddleName] LANGUAGE 'English')
KEY INDEX [PK_Person_BusinessEntityID]ON ([SearchEmp], FILEGROUP [PRIMARY])
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM)

  GO

Declare @FirstName Nvarchar(200)='KEN'
Declare @LastName  nvarchar(200)='Sánchez'
Declare @Searchtext nvarchar(400)

-- build search text avoid spaces and special characters in words
SET @Searchtext= concat(TRIM(@FirstName),' OR ', TRIM(@LastName)) 

--- First and Last Name
select top 3 * from [Person].[Person]
where Contains((FirstName,LastName),@Searchtext)

--First Name
SET @Searchtext=@FirstName
select top 3 * from [Person].[Person]
where Contains((FirstName,LastName),@Searchtext)

--Last Name
SET @Searchtext=@LastName
select  top 3* from [Person].[Person]
where Contains((FirstName,LastName),@Searchtext)

-- use ContainsTable
SET @Searchtext=@LastName
select top 3 * from ContainsTable([Person].[Person],(FirstName,LastName),@Searchtext) CT
Inner join [Person].[Person] P ON CT.[Key] = P.BusinessEntityID


您可以使用权重排序结果(sql server加权全文搜索)

goucqfw6

goucqfw62#

像这样的东西对你有用。

SELECT FirstName,
   LastName,
   Address1,
   EmployeeCode,
   OtherFields
   FROM SomeTable
   WHERE ((@FirstName IS NULL) OR ( FirstName = @FirstName)) AND
   ((@LastName IS NULL) OR ( LastName = @LastName)) AND
   ((@Address1 IS NULL) OR ( Address1 = @Address1)) AND
   ((@EmployeeCode IS NULL) OR ( EmployeeCode = @EmployeeCode))
jmp7cifd

jmp7cifd3#

使用表值函数,例如:

CREATE FUNCTION udfSearchEmployee (
    @FirstName varchar(255),
    @Lastname varchar(255),
    ...
)
RETURNS TABLE
AS
RETURN

SELECT FirstName,
       LastName,
       AddressLine,
       EmployeeCode,...
       FROM YourTable
 --To make your query SARGable
       WHERE ((@FirstName IS NULL) OR ( FirstName = @FirstName)) AND
       ((@LastName IS NULL) OR ( LastName = @LastName)) AND
       ((@AddressLine IS NULL) OR ( AddressLine = @Address1)) AND
       ((@EmployeeCode IS NULL) OR ( EmployeeCode = @EmployeeCode)) ...

相关问题