0

I have created a student table and has the following records.

enter image description here

I want to perform search on the same table. I tried with the following query.

SELECT * FROM Students WHERE Name LIKE '%AM%'

It returns First two rows as resultset, which is correct.

I would like to perform the same query using the keyword CONTAINS, instead of LIKE.

I tried the below query, but its not returning any resultset.

SELECT * FROM Students WHERE CONTAINS(Name,'"AM"')
SELECT * FROM Students WHERE CONTAINS(Name,'"AM*"')
SELECT * FROM Students WHERE CONTAINS(Name,'"*AM*"')

Kindly help me to resolve this.

Thanks in advance.

Sanoop
  • 119
  • 1
  • 2
  • 11

2 Answers2

0

Define Full-Text Index for your table column and execute your query.

sample to add Full-Text Index : Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

Community
  • 1
  • 1
Aje707707
  • 13
  • 2
0
  1. Start MSSQLFDLauncher (SQL Server -> Config Tools -> Config Manager -> Full-text Filter Daemon Launcher -> Start)
  2. Run this code (or something like this with your necessary index)

    CREATE UNIQUE INDEX IX_ID ON Students(ID)

    CREATE FULLTEXT CATALOG Students_Catalog

  3. You can't use full-text search with the middle of the word, using CTE is not correct too (because of full-text index), so we'll try to use some tricks...

  4. Add function that split names and make each letter like a word

    /* Author: Paul Simpson (modified by Alex Peshik for test purposes!) Create date: 7/19/2012 (modified 5/6/2014) Description: Puts spaces+underscores between letters. Example: "GEORGE" becomes "_G _E _O _R _G _E" */

CREATE FUNCTION udf_PutSpacesBetweenChars

(@String VARCHAR(100))

RETURNS VARCHAR(100)
AS
BEGIN
   DECLARE @pos INT, @result VARCHAR(100); 
   SET @result = @String; 
   SET @pos = 2 -- location where we want first space 
   WHILE @pos < LEN(@result)+1 
   BEGIN 
       SET @result = STUFF(@result, @pos, 0, SPACE(1));
       SET @result = STUFF(@result, @pos+1, 0, '_') -- add underscore (to imitate word)
       SET @pos = @pos+3; -- (the original was +2)
   END 
   RETURN '_'+@result; -- add leading underscore (the original is w/o it)
END
  1. Add new column and index on it (we can't use persisted computed column as far as it's non-deterministic column).

    ALTER TABLE Students ADD NameSpaced varchar(100)

    UPDATE Students SET NameSpaced=dbo.udf_PutSpacesBetweenChars(Name)

    CREATE FULLTEXT INDEX ON Students (NameSpaced) KEY INDEX IX_ID ON Students_Catalog;

  2. Use special technique to search near letters/'words'. Distance between words is 1, TRUE means only that order ("a,m" and not "m,a").

    SELECT * from Students WHERE CONTAINS(NameSpaced,' NEAR((_a,_m),1,TRUE) ')

Sorry that solution is quite huge, I have no ideas how to simplify it...

Alex Peshik
  • 1,515
  • 2
  • 15
  • 20