For this type of process, you need to split
the data that is in the attachment
column. I use something similar to this to Split
strings (there are many ways to split strings, you can search online for other functions):
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
Since this returns a table, you can join on the data. So your query would look like this:
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
See SQL Fiddle With Demo
If you want to just replace the values from the attachment
field with the correct names, you can use the Split
function and CTE
in one step:
;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
See SQL Fiddle with Demo