I would like to create a function that returns a comma separated list of field name for any given table. The function should accept database, schema and table name as input as return the comma separated list.
I can do this in a stored procedure but I want to do this in a function so I can join it into datasets. However I am problems with dynamic sql is not allowed in function - so how can I do this?
here is the proc which i want to duplicate in a function
alter proc dbo.usp_generate_column_name_string
@database varchar(100),@schema varchar(100), @table varchar(100)
as
declare @str varchar(max) = '
select stuff((select '','' + name as [text()] from
(
select c.name from ' + @database + '.sys.tables a
inner join ' + @database + '.sys.schemas b on a.schema_id = a.schema_id
inner join ' + @database + '.sys.columns c on c.object_id= a.object_id
where b.name = '''+@schema+''' and a.name ='''+@table+''') x
for xml path ('''')),1,1,'''')
'
exec (@str)
go
exec dbo.usp_generate_column_name_string 'test' , 'dbo','jl1_tmp'