Sometimes, you need to retrieve a concatenated string from one column of a table without using the cursor. To do this, you can use string aggregation. Here’s how:
- Create & fill the table using this script:
--Create Table Cust(CustID int,CustName varchar(20))Insert into Cust Values(1,'Rohit')Insert into Cust Values(2,'Amit')Insert into Cust Values(3,'Sumit')Insert into Cust Values(3,'Punit')
- Execute this script:
Declare @Names Varchar(2000)Select @Names=Isnull(@Names+','+CustName,CustName)From CustSelect @Names
- You will get this result:
Rohit,Amit,Sumit,Punit(1 row(s) affected)