在SQL Server 2016+中,您可以使用string_split()
。
在SQL Server预-2016,在common table expression使用由杰夫MODEN一个CSV分路器表值函数cross apply()
:
create table t (ID int,RecordNote varchar(32));
insert into t values
(1,'1:15&2:30&3:40')
,(2,'2:50&1:40&3:50')
,(3,'2:60&1:30&4:50')
,(4,'3:50&1:40&2:60')
,(5,'7:50&2:40&3:60');
create table p (patternId int, Pattern varchar(32));
insert into p values (1,'3:50'),(2,'2:60');
;with cte as (
select
t.Id
, RecordNote = s.Item
, RecordNoteMatches = count(*) over (partition by t.Id)
from t
cross apply dbo.delimitedsplit8K(t.RecordNote,'&') s
inner join p
on p.Pattern = s.Item
)
select *
from cte
where RecordNoteMatches = (select count(*) from p);
rextester 演示:http://rextester.com/KKTR95367
回报:
+----+------------+-------------------+
| Id | RecordNote | RecordNoteMatches |
+----+------------+-------------------+
| 4 | 3:50 | 2 |
| 4 | 2:60 | 2 |
+----+------------+-------------------+
拆分字符串参考:
如果你只是想在Id
S上的比赛,那么你就可以简化查询:
;with cte as (
select
t.Id
, RecordNoteMatches = count(*)
from t
cross apply dbo.delimitedsplit8K(t.RecordNote,'&') s
inner join p
on p.Pattern = s.Item
group by t.Id
)
select *
from cte
where RecordNoteMatches = (select count(*) from p);
rextester 演示:http://rextester.com/RDZWF26107
回报:
+----+-------------------+
| Id | RecordNoteMatches |
+----+-------------------+
| 4 | 2 |
+----+-------------------+
你的根本问题是你错误地表示了数据。您不应该将事物列表存储为字符串。你应该为每个TableA.Id和Pattern创建另一个表。 –
最初的模式是在一列'3:50&1:-1&2:60',我想使用此模式搜索,但有一些条件 1-使用ID删除-1,所以我的模式将是'3:50&2:60 ' 2-删除&因为reocrdNotes不存储& 所以我使用拆分字符串函数来获取表格中的模式 –