根据某些情况进行搜索

时间:2019-04-30 09:17:27

标签: sql sql-server stored-procedures

SQL Server中有一个表;比如说TableA有两列(名称和描述),并且其中的数据是:

Name          Description
Person1       Description1
Person2       Description2
Person12      Description12

,我有一个searchstring =“ Person + 1” 因此,它将执行的操作是搜索表中名称或描述字段包含“ Person”和“ 1”的所有值,即搜索值之间用空格分隔

我试图基于'+'分割搜索字符串,然后尝试比较满足我期望条件的表中的所有值

Declare @searchstring varchar(50)
set @searchstring='Person+1'

Select *
from TableA
where Name In Split(searchstring,'+') or
      Description In Split(searchstring,'+')

预期结果:

Name          Description
Person1       Description1
Person12      Description12

4 个答案:

答案 0 :(得分:0)

我认为您想要的语法是:

Select *
from TableA
where Name In (select value from Split(@searchstring, '+')) or
      Description In (select value from Split(searchstring, '+'));

在SQL Server 2016之前,您需要找到自己的split()函数。网上有很多例子。

答案 1 :(得分:0)

首先,您必须创建此功能(我在网上找到的功能)

CREATE FUNCTION [dbo].[SplitLike](@String varchar(MAX), @Delimiter char(1), @StrVal varchar(50), @EndVal varchar(50))
returns @temptable TABLE (items varchar(MAX))       
as       
begin      
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@StrVal + @slice + @EndVal)

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return 
end;

现在是查询

--Search Query
DECLARE @query AS VARCHAR(100) = 'Person+2'

--Create Temp Table
DECLARE @Prefixes TABLE (Prefix VARCHAR(100))

--Calling SplitLike function to get each item with '%' to apply like operator
INSERT INTO @Prefixes (Prefix)
SELECT * FROM [dbo].[SplitLike](@query, '+', '%', '%')

SELECT DISTINCT Search.* FROM Search 
LEFT JOIN @Prefixes pfn ON Search.Name LIKE pfn.Prefix 
LEFT JOIN @Prefixes pfd ON Search.[Description] LIKE pfd.Prefix

答案 2 :(得分:0)

您可以使用简单的Replace函数来替换搜索字符串中的分隔字符。

Declare @searchstring varchar(50)
set @searchstring='Person+1'

Select *
from TableA
where (Name LIKE REPLACE(@searchstring,'+','')+'%' or
      Description LIKE REPLACE(@searchstring,'+','')+'%')

答案 3 :(得分:0)

split函数与@Aamir的函数相同。请参阅上面。

查询部分:

SELECT t1.[name]
FROM #Table1 t1
CROSS APPLY #Table2 t2
GROUP BY t1.[name]
HAVING SUM(CASE WHEN (t1.[name] LIKE '%' + t2.[name] + '%') THEN 1 ELSE 0 END) = (SELECT COUNT(*) FROM #Table2)