Mario Guadanhim Mario Guadanhim - 1 month ago 20
SQL Question

Searching for words using phrase SQL Server Query

I would like to create a query which would be able to use a the words of a phrase in my "criteria" (like google does)

Example:
My phrase: 'Foo Bar Test'

My database table:

|Column|

'Hi Bar'

'Test Bar'

'Hi Foo'

'Nothing here'

'Foo again'

Result that i'm waiting for:

|Column|

'Hi Bar'

'Test Bar'

'Hi Foo'

'Foo Again'

Answer

Any split/parse function can help

Declare @YourTable table (YourFieldName varchar(100))
Insert Into @YourTable values
('Hi Bar'),
('Test Ba'),
('Hi Foo'),
('Nothing here'),
('Foo again')

Declare @SearchString varchar(max) = 'Foo Bar Test'

Select A.*
 From  @YourTable A
 Join  [dbo].[udf-Str-Parse](@SearchString,' ') B
   on  Charindex(RetVal,YourFieldName)>0

Returns

YourFieldName
Hi Foo
Foo again
Hi Bar
Test Ba

The UDF if needed

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From (Select x = Cast('<x>'+ Replace(@String,@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')