Making Rows of a Column in a Table into a Single Row in SQL Server
Hello everyone,
In this article, I will give information about converting the rows of a column in a table into a single row in SQL Server.
In SQL Server, in some cases, we may want to combine the rows of a column in a table into a single row.
You can easily do this using the code below.
--Method 1
DECLARE @Categories VARCHAR(8000);
SELECT @Categories = COALESCE(@Categories + ', ', '') + ISNULL(CategoryName, 'N/A')
FROM dbo.Categories;
PRINT @Categories
--Method 2
SELECT STUFF(
(
SELECT N', ' + CategoryName FROM dbo.Categories FOR XML PATH(''), TYPE
).value('text()[1]', 'nvarchar(max)'),
1,
2,
N''
);
When you run the above code, you will get a result similar to the one below.
As you can see, we have combined the rows of a column in the table into a single row in SQL Server.
Good luck to everyone in business and life.