Let say I have this 2 table
+----+---------+ +----+-----------+----------------+
| Id | Country | | Id | CountryId | City |
+----+---------+ +----+-----------+----------------+
| 1 | USA | | 1 | 1 | Washington, DC |
+----+---------+ +----+-----------+----------------+
| 2 | Canada | | 2 | 2 | Ottawa |
+----+---------+ +----+-----------+----------------+
| 3 | 1 | New York |
+----+-----------+----------------+
| 4 | 1 | Baltimore |
+----+-----------+----------------+
I need to produce a result like:
Id | Country | Cities
---+---------+--------------------------------------
1 | USA | Washington, DC, New York, Baltimore
---+------------------------------------------------
2 | Canada | Ottawa
So far, I am looping through the left side table result like this:
DECLARE @table
(
Id INT IDENTITY(1, 1),
CountryId INT,
City VARCHAR(50)
)
DECLARE @tableString
(
Id INT IDENTITY(1, 1),
CountryId INT,
Cities VARCHAR(100)
)
INSERT INTO @table
SELECT Id, City
FROM tblCountries
DECLARE @city VARCHAR(50)
DECLARE @id INT
DECLARE @count INT
DECLARE @i INT = 1
SELECT @count = COUNT(*) FROM @table
WHILE (@i <= @count)
BEGIN
SELECT @Id = Id, @city = City FROM @table WHERE Id = @i
IF(EXISTS(SELECT * FROM @tableString WHERE CountryId = @Id))
BEGIN
UPDATE @tableString SET Cities = Cities + ', ' + @city WHERE Id = @Id
END
ELSE
BEGIN
INSERT INTO @tableString (CountryId, city) VALUES (@Id, @city)
END
SET @i = @i + 1
END
SELECT tc.Id, tc.Country, ts.Cities
FROM tblCountries tc
LEFT JOIN @tableString ts
ON tc.Id = ts.CountryId
My concern is that with all those looping in TSQL, it may be a performance killer. Even with fewer, it appears to be slow. Is there a better way to concatenate those string without having to loop through the data set as if I was working in C# . Thanks for helping