Friday, May 6, 2011

Match closest phrase in SQL

I need to write a query in t-sql or linq that matches db records that contain the most of the user input words.

exmaple: nvarchar field in db: "The quick brown fox jumps over the lazy dog"

User input: "brown cow"

The program would match that record because it has the word brown.

let me know if i need to provide more examples.

From stackoverflow
  • We generally use a UDF to split a string into tabular data and can use like command for the same.

    declare @searchStr nvarchar(100)
    set @searchStr = 'brown fox'
    selecT T.* from test T, dbo.fnc_SplitSTring(@searchStr,' ')
    where   T.name like '%' + token + '%'
    
    
    CREATE   FUNCTION [dbo].[fnc_SplitString]
    (
    @InString varchar(8000),
    @Delim char(1)
    )
    RETURNS @Return table
    (
    Position int identity,
    Token varchar(100) -- Maximum token size is 100 chars...
    )
    As
    BEGIN
        Declare @CR varchar(1),
        @LF varchar(1)
        Set @CR = char(10)
        Set @LF = char(13)
        -- 
        If @InString is null return
        -- 
        Declare @Pos int
        Declare @Pattern char(3)
        Set @Pattern = '%' + @Delim + '%'
        -- 
        Declare @Token varchar(30)
        SELECT @InString = @InString + @Delim -- add trailing delimiter
        SELECT @Pos = PATINDEX(@Pattern, @InString)
        WHILE (@Pos <> 0) BEGIN
         SELECT @Token = ltrim(rtrim(SUBSTRING(@InString, 1, @Pos - 1)))
         Select @Token = replace(@Token, @CR, '')
         Select @Token = replace(@Token, @LF, '')
         Insert @Return Values (@Token)
         SELECT @InString = STUFF(@InString, 1, PATINDEX(@Pattern, @InString),'')
         SELECT @Pos = PATINDEX(@Pattern, @InString)
        END
    -- 
    return
    -- 
    END
    
  • Assuming you're using T-SQL in a MS SQL Server environment, then you should use Full Text Search technology. It gives you the speed and keeps you away from reinventing the wheel.

    taoufik : Officially, not yet. You can use LINQ calling a stored procedure or Check this link for a custom solution http://sqlblogcasts.com/blogs/simons/archive/2008/12/18/LINQ-to-SQL---Enabling-Fulltext-searching.aspx

0 comments:

Post a Comment