用'+'分割字符串并搜索表中的所有行是否都存在

问题描述

我有一个表格规则,其中有2列:

  1. RID
  2. RuleValue

DECLARE @RuleType VARCHAR(MAX)= 'DDDD+FFFF' ;

我想在'DDDD+FFFF'列中拆分并搜索上述变量rulevalue

下面的图像是规则表:

enter image description here

rulevalue列中进行拆分和搜索之后,输出应如下所示:

enter image description here

解决方法

如果顺序无关紧要,则可以从变量中创建条件,然后将其与like子句中的where过滤器一起使用:

declare @Rules  table (RID int,RuleValue varchar(50))

insert into @Rules
values 
 (1,'DDDD+FFFF'),(2,'DDDD+EEEE+FFFF'),(3,'BBBB+CCCC'),(4,'BBBB+DDDD'),(5,'CCCC+EEEE'),(6,'BBBB+DDDD')

DECLARE @RuleType VARCHAR(MAX)= 'DDDD+FFFF' ;

select *
from @Rules
where RuleValue like '%' + replace(@RuleType,'+','%') + '%'

结果:

enter image description here


根据OP的评论进行编辑

如果顺序很重要,那么解决方案会比较棘手。

declare @Rules table (RID int,'BBBB+DDDD')

DECLARE @RuleType VARCHAR(MAX)=  'DDDD+FFFF+EEEE' ;

--define a table variable to hold every component of the rule type
declare @splittedRules table (SplittedRule nvarchar(max))

--fill the table variable with each component of the rule type
--since you use SQL Server 2012 you must use xml syntax to split the string
insert into @splittedRules
SELECT Split.a.value('.','NVARCHAR(MAX)') as SplittedRule
FROM
(
    SELECT CAST('<X>'+REPLACE(@RuleType,'</X><X>')+'</X>' AS XML) AS String
) AS A
CROSS APPLY String.nodes('/X') AS Split(a)

--now you can see if each rule matches a single component of the rule type
;with compare as 
(
    select 
        r.RID,r.RuleValue,spl.SplittedRule,case when CHARINDEX(spl.SplittedRule,r.RuleValue) > 0 then 1 else 0 end as ok 
    from 
        @Rules as r 
            cross apply 
        @splittedRules spl
)
--finally you can perform a group by checking 
--which rule matches all the components of the rule type
select
    RID,RuleValue   
from 
    compare
group by 
    RID,RuleValue
having 
    sum (ok)=(select count(*) from @splittedRules)
order by RID

结果:

enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...