STUFF Function in SQL Server
We can concatenate multiple rows within a single row using the predefined function STUFF available in SQL Server. Here is the example.
Step 1Create a database.
For example: StudentCourseDB (in my example)
Step 2
Create 2 tables as in the following.
- Courses
Add some records to the Courses table, for example:- Create Table Courses
- (
- CourseID int primary key,
- CourseName nvarchar(20)
- )
- INSERT INTO Courses(CourseId,CourseName) VALUES (1,'C#')
- INSERT INTO Courses(CourseId,CourseName) VALUES (2,'ASP.Net')
- INSERT INTO Courses(CourseId,CourseName) VALUES (3,'MVC')
- INSERT INTO Courses(CourseId,CourseName) VALUES (4,'WCF')
- INSERT INTO Courses(CourseId,CourseName) VALUES (5,'Share Point')
- INSERT INTO Courses(CourseId,CourseName) VALUES (6,'WPF')
- INSERT INTO Courses(CourseId,CourseName) VALUES (7,'SQL Server')
- INSERT INTO Courses(CourseId,CourseName) VALUES (8,'JQuery')
- SELECT * FROM Courses

- StudentCourses
Add some records into the StudentCourses table, for example:- CREATE TABLE StudentCourses
- (
- StudentID int,
- CourseID int
- )
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,1)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,3)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (1,5)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,2)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,4)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (2,5)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (3,3)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (3,6)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (4,7)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (4,8)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (5,1)
- INSERT INTO StudentCourses(StudentID, CourseID) VALUES (5,2)
- SELECT * FROM StudentCourses




Bhavin TankPosted Feb 18, 2020, 3:17 AM
Very usefull content
rukmini mPosted Aug 14, 2019, 6:08 AM
If i dont want to separate with comma what shud i do? if i delete comma, my first letter is getting missed
VandanaPosted Aug 9, 2019, 1:58 AM
Helpful thank you
Anu VPosted Mar 29, 2018, 12:21 AM
Thank you show much, it helped me lot.
Murugan PalanisamyPosted Oct 22, 2016, 3:36 AM
Thank you show much, it helped me lot.
Dinesh BeniwalPosted Mar 15, 2015, 11:44 AM
Thanks for sharing.
Rahul Kumar SaxenaPosted Mar 15, 2015, 6:41 AM
Good Show..