Using a full text query, you can give the end user more flexibility in how they build their search. Also, you donโt need to parse the search string so many times, and the search is usually faster than using LIKE.
1. Create a full text directory and index.
CREATE FULLTEXT CATALOG [ftcat_Books] WITH ACCENT_SENSITIVITY = OFF GO CREATE FULLTEXT INDEX ON [Books] ([Title] LANGUAGE 'English', [Board] LANGUAGE 'English', [Class] LANGUAGE 'English') KEY INDEX [PK_Books] ON ([ftcat_Books], FILEGROUP [PRIMARY]) WITH (CHANGE_TRACKING = AUTO, STOPLIST = OFF)
Your Books.Class column must be varchar or nvarchar for this.
I recommend not using stop lists ( STOPLIST = OFF ), so that single digits, for example 9 in your example, are not ignored.
More emphasis on sensitivity (in this example does not use Accent sensitivity)
Learn more about change tracking (This example uses change tracking)
2. Convert user queries to Boolean syntax.
When the user types 9 CBSE , he must be converted to "9" AND "CBSE" . Each term must be surrounded by double quotation marks and separated by an AND. (You can also use the characters OR, NOT, NEAR and wildcards, but I'm not sure if you need them in your case.)
Here is an easy way to convert to Boolean syntax that you need using the .NET regular expression (basically, replace each series of 1+ spaces with " AND " and surround the result with more double quotes):
// assume searchString = "9 CBSE" string searchStringBoolean = "\"" + Regex.Replace(searchString, @"\s+", "\" AND \"") + "\"";
Keep in mind that this is a very simple approach. You will need to consider what to do if the user has already typed double quotes or AND in their search bar.
3. Run the full text query.
-- @SearchStringBoolean is the boolean string created in step 2 SELECT TOP 100 Books.Title, Books.Board, Books.Class FROM ContainsTable(Books, *, @SearchStringBoolean) as FullTextResults join Books on FullTextResults.KEY = Books.Id ORDER BY FullTextResults.RANK desc
This returns the top 100 matches with the best matches sorted first.