How to combine multiple rows into one cell in a SQL Server table (T-SQL)

Introduction

This T-SQL script will demo how to combine multiple rows into one cell in a SQL Server table.  

Scenarios

As many people asked how to combine multiple rows into one cell in a SQL Server table, this script will provide some convenience.

Script

You can use this script in this way:
1. Open SQL Server Management Studio (SSMS) and connect to SQL Server.
2. Copy the code from CombineRowsIntoOneRow.sql, paste it in a new query and run the script.

After the script finishes running, we’ll get the following figure:

Here are some code snippet for your reference: 

SQL
Edit|Remove
SELECTcolumn1, 
    STUFF((SELECTCAST(','ASvarchar(max)) + column2FROM@InitialTableasbWHEREb.column1 = a.column1FORXMLPATH(''), TYPE 
            ).value('.''varchar(max)' 
         ),11,''AScolumn2FROM 
    (SELECTDISTINCTcolumn1FROM@InitialTable ) ASaGO

 

Prerequisites

SQL Server 2008 or higher version