How To Create a Comma Separated List Of Table Columns Using T-SQL



TODO:

Have you ever wanted to get a comma separated list of columns that belong to a table using T-Sql?

 

SOLUTION:

DECLARE @columnList varchar(8000)
DECLARE @name varchar(100)
DECLARE db_cursor CURSOR FOR  
	SELECT   COLUMN_NAME
		FROM    INFORMATION_SCHEMA.COLUMNS 
		WHERE    TABLE_NAME = 'MyTable'
		ORDER BY  COLUMN_NAME ASC;
SET @columnList=''
	
OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN  
		IF @columnList='' 
			SET @columnList = '[' + @name + ']'
		ELSE
			SET @columnList = @columnList + ',[' + @name + ']'
		
       FETCH NEXT FROM db_cursor INTO @name   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor 

SELECT @columnList

 

NOTES:

Just paste to a query window, hit ctrl-a and F5 to run it.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading