如果顺序无关紧要,您可以从变量创建条件,然后在 where 子句中将其与 like 过滤器一起使用:
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, 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+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
结果: