The other day I had to concatenate a query result. In this article, I’m going to tell you how to do this through an example.
Example:
Let’s create a table like below and add a few records into this table.
1 2 3 4 5 |
CREATE TABLE [dbo].[ConcatenateResultsExample]( [myString] [varchar](50) NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[ConcatenateResultsExample] VALUES('1'),('2'),('3'),('4'),('4'),('5') |
If we want to read the data in this table, we will see the result as follows.
1 |
Select * FROM [dbo].[ConcatenateResultsExample] |
Let’s concatenate this result set. You can perform this operation with the help of the following script.
1 2 3 4 5 |
DECLARE @concatenatedresult varchar(50) SET @concatenatedresult = '' SELECT @concatenatedresult = @concatenatedresult + myString + ', ' FROM [dbo].[ConcatenateResultsExample] SELECT @concatenatedresult; |