This stored procedure is suitable for solving your problem. He uses the cursor. Maybe there is a way to remove the cursor, but so far it has failed. So this decision turned out.
CREATE Procedure [dbo].[spGetResult] As Begin declare @curPNL cursor declare @pnlid int declare @Line varchar(10), @TotalisationId varchar(20), @Totalisation varchar(50) declare @spresult table(PNLId int, Line varchar(10), TotalisationId varchar(20), result varchar(4000)); --declare the cursor set @curPNL = cursor for select PnlId, Line, TotalisationId, totalisation from PNLTable where designation = 'Formule' open @curPNL Fetch Next From @curPNL into @pnlId, @Line, @TotalisationId, @Totalisation While @@FETCH_STATUS = 0 Begin declare @nsql nvarchar(4000); declare @table table(tname varchar(50)); declare @result varchar(4000) delete from @table --get the totalisation data for specific column set @nsql = 'select totalisation from PNLTable Where Line in (''' + replace(@Totalisation,'+',''',''') + ''')'; print 'Calling child' insert into @table exec(@nsql); set @result = ''; if not exists (select 1 from @table) Begin set @result = replace(@Totalisation,'+','|') End else Begin --get the values of totalisation in a pipe separated string select @result = case when @result = '' then '' else @result + '|' end + tname from @table; End --insert the values in the temporary table insert into @spresult(PNLId, Line, TotalisationId, result) select @pnlid, @Line, @TotalisationId, @result Fetch Next From @curPNL into @pnlId, @Line, @TotalisationId, @Totalisation End close @curPNL deallocate @curPNL select * from @spresult; End
Although the structure of the table was not very clear to me. But I created the following script to create a table and insert data.
CREATE TABLE [dbo].[PNLTable]( [PnlId] [int] NOT NULL, [Line] [varchar](10) NULL, [TotalisationId] [varchar](20) NULL, [Designation] [varchar](20) NULL, [Totalisation] [varchar](50) NULL, PRIMARY KEY CLUSTERED ( [PnlId] ASC ) )
- insert data
INSERT [PNLTable] ([PnlId], [Line], [TotalisationId], [Designation], [Totalisation]) VALUES (1, N'A', N'Gross Fees', N'Formule', N'A01+A02+A03+A04+A05'), (2, N'A01', N'GF1', N'Comptes', N'99999') ,(3, N'A02', N'GF2', N'Comptes', N'99998'), (4, N'A03', N'GF3', N'Comptes', N'99991'), (5, N'A04', N'GF4', N'Comptes', N'99996') , (6, N'A05', N'GF5', N'Comptes', N'999995'), (14, N'B1', N'Perm', N'Formule', N'12+14+25')