Find nearest phrase in SQL
I need to write a query in t-sql or linq that matches db records that contain most of the user entered words.
exmaple: nvarchar field in db: "The quick brown fox jumps over the lazy dog"
User input: "brown cow"
The program will match this entry because it has the word brown.
let me know if I need to provide more examples.
0
decon
a source
to share
2 answers
We usually use UDF to split a string into tabular data and can use the same command for it.
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
+1
a source to share
Assuming you are using T-SQL in MS SQL Server environment, you should use Full Text Search technology . This gives you speed and prevents you from reinventing the wheel.
+2
a source to share