使用短语SQL Server Query搜索单词

我想创建一个查询,它可以在我的“条件”中使用短语的单词(就像谷歌一样)

例:
我的短语:’Foo Bar Test’

我的数据库表:

|栏|

‘嗨吧’

‘测试栏’

‘你好’

‘这里没有什么’

再次’Foo’

我正在等待的结果:

|栏|

‘嗨吧’

‘测试栏’

‘你好’

‘再次’Foo’

最佳答案 任何拆分/解析功能都可以提供帮助

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

返回

YourFieldName
Hi Foo
Foo again
Hi Bar
Test Ba

UDF如果需要的话

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',' ')
点赞