TSQL -选择包含列表中所有项目的行



提供了一个逗号分隔字符串形式的关键字列表。我需要看看在一个数据库表中的列,并返回所有的行,这列包含所有的关键字在任何顺序。只要该列包含所有关键字,我就返回该行。

例如:

HeroId    HeroName               
--------  -------------------------
1         Ironman              
2         Superman               
3         Spiderman               
4         Otherman 

查询字符串:'er,man,s'

预期结果:Superman,Spiderman

说明:只有SupermanSpiderman包含关键字ermans

我希望你能理解。

您可以使用string_split()和其他一些逻辑:

select t.heroid, t.heroname
from t cross apply
string_split(@query, ',') s
on t.heroname like concat('%', s.value, '%')
group by t.heroid, t.heroname
having count(distinct s.value) = (select count(distinct ss.value) from string_split(@query, ',') ss);

最新更新