Concatenate Query Result
There are cases we want to concatenate the result of our query to display single row result. Normally we use cursor to concatenate results but cursor is a very expensive query and complicated to use.
Concatenate Using COALESCE
USE [AdventureWorks] GO DECLARE @Data VARCHAR(2000) SELECT @Data = COALESCE(@Data + ',' + NationalIDNumber, NationalIDNumber) FROM HumanResources.Employee PRINT @Data
Result:
10708100,109272464,112432117,112457891,113393530,113695504,121491555,1300049,131471224,132674823...
If the column you want to concatenate is non-string datatype you can use CONVERT or CAST to convert it to string data type.
Dynamic Pivot Column
We can also use this trick in PIVOT operator to make pivot columns dynamic. Here is the trick.
Pivot using COALESCE (Dynamic Column)
DECLARE @Data VARCHAR(2000) DECLARE @Query VARCHAR(MAX) SELECT TOP 12 @Data = COALESCE(@Data + ',[' + ISNULL([Name], 'NA') + ']', '[' + ISNULL([Name], 'NA') + ']') FROM Production.ProductModel SET @Query = 'SELECT Category, ' + @Data + ' FROM ( SELECT B.[Name] AS Category, D.[Name] AS ProductModel, C.Quantity FROM Production.Product A INNER JOIN Production.ProductSubCategory B ON A.ProductSubCategoryID = B.ProductSubCategoryID INNER JOIN Production.ProductInventory C ON A.ProductID = C.ProductID INNER JOIN Production.ProductModel D ON A.ProductModelID = D.ProductModelID WHERE A.ProductSubCategoryID IS NOT NULL ) AS Product PIVOT ( SUM(Quantity) FOR ProductModel IN ( '+ @Data + ' ) ) AS ProductPivot ORDER BY Category' EXEC(@Query)
Normal Pivot Query
SELECT Category, [Sport-100], [Mountain Bike Socks], [Long-Sleeve Logo Jersey] FROM ( SELECT B.[Name] AS Category, D.[Name] AS ProductModel, C.Quantity FROM Production.Product A INNER JOIN Production.ProductSubCategory B ON A.ProductSubCategoryID = B.ProductSubCategoryID INNER JOIN Production.ProductInventory C ON A.ProductID = C.ProductID INNER JOIN Production.ProductModel D ON A.ProductModelID = D.ProductModelID WHERE A.ProductSubCategoryID IS NOT NULL ) AS Product PIVOT ( SUM(Quantity) FOR ProductModel IN ( [Sport-100], [Mountain Bike Socks], [Long-Sleeve Logo Jersey] ) ) AS ProductPivot ORDER BY Category
The normal query has fixed PIVOT column. On the other hand using COALESCE we can make the columns dynamic.