sql server - Add comma separated input to table column -


i have table have 3 column in it

agent_listing_company>- listingid, agentid, companyid 

i want insert comma separated input in it. input like

listingid = '5',  agentid = '6,7,8', companyid = '9,10,11' 

i using query insertion not working

insert  dbo.agent_listing_company                         (  listingid ,                           agentid ,                           companyid                         )                         select  5, item ,                                 (select item dbo.fn_split('9,10,11' , ','))                            dbo.fn_split('6,7,8', ',') 

--here dbo.fn_split('6,7,8', ',')split companyids, how split 2 inputs. saved value after insertion in table should be

listingid, agentid, companyid    5         6          9    5         7          10    5         8          11 

my dbo.fn_split('6,7,8', ',') function is...

use [xrc] go /****** object:  userdefinedfunction [dbo].[fn_split]    script date: 6/3/2015 10:04:07 ******/ set ansi_nulls on go set quoted_identifier on go  alter function [dbo].[fn_split]( @str varchar(max), @delimiter char(1) ) returns @returntable table (idx int primary key identity, item varchar(8000)) begin declare @pos int select @str = @str + @delimiter while len(@str) > 0  begin     select @pos = charindex(@delimiter,@str)     if @pos = 1         insert @returntable (item)             values (null)     else         insert @returntable (item)             values (substring(@str, 1, @pos-1))     select @str = substring(@str, @pos+1, len(@str)-@pos)        end return end 

try this

insert agent_listing_company (  listingid ,                           agentid ,                           companyid                         ) select  5, a.item , b.item dbo.fn_split('6,7,8', ',') inner join dbo.fn_split('9,10,11' , ',') b on a.idx = b.idx 

Comments