All Rows value into comma seprated values into one single variable

declare @SQLCol nvarchar(max), @TableName nvarchar(max)
select @SQLCol = COALESCE(@SQLCol+’,',”)+ sc.COLUMN_NAME FROM information_schema.columns sc
where sc.COLUMN_NAME like ‘%ColumnName%’ and sc.TABLE_NAME = @TableName
order by sc.COLUMN_NAME asc

Print @SQLCol

Note:
COALESCE() : This function returns single value of collect all the values with user defined format. Here for each records i used ‘,’ but you can use anything you want for seperation. This is very good function provided by SQL server.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.