Click here to Skip to main content
14,494,314 members
Rate this:
Please Sign up or sign in to vote.
problem

How to separate value exist on temp table dynamically separated by comma ?

i work on sql server 2012 i need to separate field TeamName by comma

teamname ,teamname+'Date'

i need to loop to teamname filed in tmp table #Teams then separate by comma and every field will be next field + 'Date'

really #temp table #teams every time changed so i dont have static data so i need any way dynamically sepatae field

and second will be field+date

i need result as
Package,PackageDate,Parametric,ParametricDate,Scribing,ScribingDate,Lifecycle,LifecycleDate

What I have tried:

CREATE TABLE #Teams
(
TeamId int,
TeamName  nvarchar(200)
)
insert into #Teams(TeamId,TeamName) values
 (1,'Package'),
 (2,'Parametric'),
 (3,'Scribing'),
 (4,'Lifecycle')
Posted
Updated 26-Mar-20 9:57am
v2
Comments
CHill60 26-Mar-20 8:42am
   
Firstly you don't need to "loop". Show us some sample data to help make it clear what you are asking - for example you have not shown us any comma separated data

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

If i understand you well... you want to convert rows into single column.

Take a look at these articles: TSQL – Concatenate Rows using FOR XML PATH() | Sql And Me[^]
STUFF AND FOR XML PATH for String Concatenation :: SQL Server[^]

You can also use CTE[^]:
DECLARE @Teams TABLE (TeamId int, TeamName  nvarchar(200))

insert into @Teams(TeamId,TeamName)
values (1,'Package'),
(2,'Parametric'),
(3,'Scribing'),
(4,'Lifecycle')

;WITH CTE AS
(
	SELECT 1 AS tid, CAST(TeamName AS VARCHAR(MAX)) AS ResultField
	FROM @Teams
	WHERE TeamId = 1
	UNION ALL
	SELECT tid+ 1,  CAST(CONCAT(c.ResultField, ',', t.TeamName) AS VARCHAR(MAX)) AS ResultField
	FROM CTE AS c INNER JOIN @Teams AS t ON c.tid +1 = t.TeamId
	WHERE EXISTS(SELECT TeamId FROM @Teams WHERE TeamId = tid+1)
)
SELECT TOP(1) ResultField 
FROM CTE 
ORDER BY tid DESC
   
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100