Sunday, October 4, 2009

sql server table columns as comma seperated string

Below function will produce the list of the columns in a table as a comma separated list. 


It will be useful especially while making generic insert statements with column names as values.

usage : select dbo.fnColList('MyTable')

create function fnColList(@in_vcTbl_name varchar(8000))
returns varchar(8000)
as
begin 
declare @colList2BuildAuditTable  varchar(max)
SELECT @colList2BuildAuditTable = coalesce(@colList2BuildAuditTable+ ',', '')+ '['+ B.NAME +']' 
FROM SYSOBJECTS A JOIN SYSCOLUMNS B ON A.ID = B.ID
WHERE A.ID = OBJECT_ID(@in_vcTbl_name)
ORDER BY B.COLORDER

return @colList2BuildAuditTable 
end 



1 comment:

Featured Post

SQL Server AWS Migration BCP

stored procedure to generate BCP scritps to migrate the SQL Server database. Developed this stored procedure on my labs to simulate t...

Contributors