对于这种类型的过程,您需要列中split
的数据attachment
。我对字符串使用了类似这样的东西Split
(分割字符串的方法有很多,你可以在网上搜索其他功能):
CREATE FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
由于这会返回一个表,因此您可以加入数据。因此,您的查询将如下所示:
select o.id,
o.name,
c.body
from orders o
left join
(
select c.body, s.items as o_id
from communications c
cross apply dbo.split(c.attachment, ',') s
) c
on o.id = c.o_id
请参阅带有演示的 SQL Fiddle
如果您只想attachment
用正确的名称替换字段中的值,您可以使用该Split
函数并CTE
一步:
;with cte as (
select o.id,
o.name,
c.body
from orders o
left join
(
select c.body, s.items as o_id
from communications c
cross apply dbo.split(c.attachment, ',') s
) c
on o.id = c.o_id
)
select distinct c2.body,
stuff((select distinct ', ' + c1.name
from cte c1
where c2.body = c1.body
for XML path('')),1,1,'') attachment
from cte c2
请参阅带有演示的 SQL Fiddle