【问题标题】:Split string with '+ 'and search whether all the strings exist in one row in table用'+'分割字符串并搜索所有字符串是否存在于表中的一行中
【发布时间】:2020-12-06 09:04:45
【问题描述】:

我有一个包含 2 列的 规则 表:

  1. RID
  2. 规则值

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

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

下图是规则表:

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

【问题讨论】:

  • 谁能回答这个问题?
  • 请相应地查看sql tag infoedit 中的指南。

标签: sql sql-server tsql sql-server-2012


【解决方案1】:

如果顺序无关紧要,您可以从变量创建条件,然后在 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

结果:

【讨论】:

  • 嗨,在某种程度上这就是我想要的。如果@RuleType = 'DDDD+FFFF+EEEE' 我们应该得到'DDDD+EEEE+FFFF' 作为输出,这可能吗?
  • @MounikaVadeghar 是的,有可能,请参阅更新的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 2021-11-16
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
相关资源
最近更新 更多