答案 0 :(得分:0)
尝试以下操作:
declare @table_A table (username varchar(1000))
declare @table_B table (username varchar(1000), email_id varchar(2000))
insert into @table_A
select 'User, AA # User, BB'
union
select 'User, CC # User, DD # User, EE'
union
select 'User, FF # User, GG # User, HH'
insert into @table_B
select 'User, AA','User.a@gmail.com'
union
select 'User, BB','User.b@gmail.com'
union
select 'User, CC','User.c@gmail.com'
union
select 'User, DD','User.d@gmail.com'
union
select 'User, EE','User.e@gmail.com'
union
select 'User, FF','User.f@gmail.com'
union
select 'User, GG','User.g@gmail.com'
union
select 'User, HH','User.h@gmail.com'
select A.username, B.email_id into #temp
from
(
select username, ltrim(rtrim(value)) val
from @table_A
cross apply string_split(username, '#')
)A
left join @table_B B on B.username = A.val
select username, ltrim(rtrim(stuff((
select DISTINCT ' # ' + u.email_id
from #temp u
where u.username = t.username
for xml path('')
),2,1,''))) as email_id
from #temp t
group by username
drop table if exists #temp
答案 1 :(得分:0)
使用STUFF
函数的另一种方式可能会很有趣
declare @TableA table (username varchar(1000))
declare @TableB table (username varchar(1000), email_id varchar(2000))
insert into @TableA values
('User, AA # User, BB'),('User, CC # User, DD # User, EE'),('User, FF # User, GG # User, HH')
insert into @TableB values
('User, AA','User.a@gmail.com'),('User, BB','User.b@gmail.com'),('User, CC','User.c@gmail.com'),
('User, DD','User.d@gmail.com'),('User, EE','User.e@gmail.com'),('User, FF','User.f@gmail.com'),
('User, GG','User.g@gmail.com'),('User, HH','User.h@gmail.com')
;with ct as (
select a.username, b.email_id
from @TableB b
inner join @TableA a on charindex(b.username, a.username) > 0
)
select username, abc = STUFF
(
(
SELECT ' # ' + email_id
FROM ct As t2
WHERE t2.username = t1.username
ORDER BY username
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
from ct t1
group by username
结果