SQL Server full-text indexing is rather easy to set up and configure. However, I ran into an issue with my current project. When doing an "AND" search, the query would simply not work. "OR" searches were fine, but "AND" simply returned zero results.
Our table looked like the following.
- CREATE TABLE [dbo].[Person] (
- [PersonID] INT NOT NULL,
- [Email] NVARCHAR (255) NOT NULL,
- [FirstName] NVARCHAR (255) NOT NULL,
- [LastName] NVARCHAR (255) NOT NULL,
- CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ([PersonID] ASC) WITH (FILLFACTOR = 90)
- );
However, every approach we took using CONTAINS, CONTAINSTABLE, FREETEXT, and FREETEXTTABLE would not work. I ran across this post which provided a workaround.
Here is how we addressed the issue. First, create the full-text catalog.
- CREATE FULLTEXT CATALOG [GlobalSearchCatalog]
- WITH ACCENT_SENSITIVITY = ON
- AUTHORIZATION [dbo];
- GO
Next, create a view that contains your search information,
- CREATE VIEW [dbo].[ParentsView] WITH SCHEMABINDING
- AS
- SELECT P.PersonID,
- P.FirstName,
- P.LastName,
- P.Email,
- P.FirstName + ' ' + P.LastName AS FullName
- FROM dbo.Person P
- GO
A couple of items to point out. In line 1, the view is schema bound. In line 7, we are creating an aggregated first and last name for the person. This is key to this technique of searching the full text index.
Next, you need to create a clustered index on your new view. This can be done because the view is schema bound.
- CREATE UNIQUE CLUSTERED INDEX [PK_ParentsView] ON [dbo].[ParentsView]
- (
- [PersonID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- GO
- CREATE FULLTEXT INDEX ON [dbo].[ParentsView]
- ([FullName] LANGUAGE 1033,
- [Email] LANGUAGE 1033)
- KEY INDEX [PK_ParentsView]
- ON [GlobalSearchCatalog];
- GO
Next, let's make a call using the full text index.
- SELECT *
- FROM Person P
- INNER JOIN CONTAINSTABLE(ParentsView, *, 'user', 250) AS Key_Tbl ON P.PersonID = Key_Tbl.[Key]
Join the conversation! Your thoughts help the community grow.