Technical Article

CSV Lists of Columns in Different Formats

,

This script creates comma separated lists of columns in different formats. These lists can be copied and pasted into other T-SQL statements.  The lists are formatted as: a simple list of column names, a list with the column names as declared variables (@ + column name + data type), a list with column names as parameters (@ + column name) and a list of columns for value assignment (column name = @ + column name). 

CREATE PROC up_GetColumnsPlus

@TableName varchar(50)

AS 

SET NOCOUNT ON

DECLARE @Separator char(1),
 @Prefix char(1)

SET @Separator = ','
SET @Prefix ='@'

SELECT CAST( COLUMN_NAME + @Separator AS varchar(30))as ColumnName
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

SELECT CAST( @Prefix + COLUMN_NAME +' '+ DATA_TYPE
 + CAST (CASE
WHEN CHARACTER_MAXIMUM_LENGTH <> 0 THEN '('+ CONVERT(varchar(7),CHARACTER_MAXIMUM_LENGTH)+'),'
ELSE ',' 
END AS varchar(7))
AS varchar(30)) 
AS Declaration
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

SELECT CAST(@Prefix + COLUMN_NAME + @Separator as varchar(30) )AS Parameter
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

SELECT CAST(COLUMN_NAME + ' = ' + @Prefix + COLUMN_NAME + ',' as varchar(70) ) AS Assignment
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating