问题描述
我有一个表格规则,其中有2列:
- RID
- RuleValue
DECLARE @RuleType VARCHAR(MAX)= 'DDDD+FFFF' ;
我想在'DDDD+FFFF'
列中拆分并搜索上述变量rulevalue
。
下面的图像是规则表:
在rulevalue
列中进行拆分和搜索之后,输出应如下所示:
解决方法
如果顺序无关紧要,则可以从变量中创建条件,然后将其与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,'+','%') + '%'
结果:
根据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
结果: