If possible you need to fix your database design on this table so you are not storing a comma separate list of values. This will be very difficult to maintain.
Ideally your table structure could be altered something like the following:
create table item_details
(
id int,
price int
);
create table foreign_details
(
id int,
details varchar(50)
);
create table item_foreign
(
item_id int,
foreign_id int
);
Then you would get the result using a query:
select i.id, i.price, f.id
from item_details i
inner join item_foreign ifd
on i.id = ifd.item_id
inner join foreign_details fd
on ifd.foreign_id = f.id
If you cannot fix your current table structure, then you can use a split function to separate the data into multiple rows. A sample function could be:
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;
Then you will use CROSS APPLY to pass in the comma separated list for each row similar to this:
select t.id, t.price,
c.items foreign_id
from yt t
cross apply dbo.split(t.LIST_OF_FOREIGN_IDS, ',') c;
See SQL Fiddle with Demo