Today I am showing you a quick and easy way to concatenate rows of textual data in a single string. This is particularly useful when you need a comma separated list of items, products etc. and you don’t want to loop the whole dataset for performance reasons.
Following is the sample code to demonstrate this. Concept is very simple and anyone can easily understand it by running the following code.
Set Nocount On
Print ‘Start’
Print ‘Creating Sample Items table’
Go
CREATE TABLE dbo.tblItems
(
ItemID int NOT NULL IDENTITY (1, 1),
ItemName nvarchar(50) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.tblItems ADD CONSTRAINT
PK_Table_1 PRIMARY KEY CLUSTERED
( ItemID )
GO
Print ‘Inserting data in sample table’
Go
Insert into dbo.tblItems (ItemName) Values (‘Item1′)
Insert into dbo.tblItems (ItemName) Values (‘Item2′)
Insert into dbo.tblItems (ItemName) Values (‘Item3′)
Insert into dbo.tblItems (ItemName) Values (‘Item4′)
Go
Print ‘Following is the comma separated list of Items’
Go
Declare @m_ItemsList nvarchar(2000)
Select @m_ItemsList=”
Select @m_ItemsList=@m_ItemsList+ItemName+‘,’ from tblItems
Select Left(@m_ItemsList,Len(@m_ItemsList)-1)
Go
Print ‘Dropping sample table’
Drop table dbo.tblItems
Go
Print ‘Finished’