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.

182 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!