Dead horse perhaps, but a while back I was trying to do the same and came across a script to create a STP that tried to do what I was looking for, but it had a few quirks that needed some attention. In an attempt to track down where I found the script to post an update, I came across this thread and it seemed like a good spot to share it.
This STP (Which for the most part I take no credit for, and I can't find the site I found it on), takes a schema name, table name, and Y or N [to include or exclude headers] as input parameters and queries the supplied table, outputting each row in comma-separated, quoted, csv format.
I've made numerous fixes/changes to the original script, but the bones of it are from the OP, whoever that was.
Here is the script:
IF OBJECT_ID('get_csvFormat', 'P') IS NOT NULL
DROP PROCEDURE get_csvFormat
GO
CREATE PROCEDURE get_csvFormat(@schemaname VARCHAR(20), @tablename VARCHAR(30),@header char(1))
AS
BEGIN
IF ISNULL(@tablename, '') = ''
BEGIN
PRINT('NO TABLE NAME SUPPLIED, UNABLE TO CONTINUE')
RETURN
END
ELSE
BEGIN
DECLARE @cols VARCHAR(MAX), @sqlstrs VARCHAR(MAX), @heading VARCHAR(MAX), @schemaid int
--if no schemaname provided, default to dbo
IF ISNULL(@schemaname, '') = ''
SELECT @schemaname = 'dbo'
--if no header provided, default to Y
IF ISNULL(@header, '') = ''
SELECT @header = 'Y'
SELECT @schemaid = (SELECT schema_id FROM sys.schemas WHERE [name] = @schemaname)
SELECT
@cols = (
SELECT ' , CAST([', b.name + '] AS VARCHAR(50)) '
FROM sys.objects a
INNER JOIN sys.columns b ON a.object_id=b.object_id
WHERE a.name = @tablename AND a.schema_id = @schemaid
FOR XML PATH('')
),
@heading = (
SELECT ',"' + b.name + '"' FROM sys.objects a
INNER JOIN sys.columns b ON a.object_id=b.object_id
WHERE a.name= @tablename AND a.schema_id = @schemaid
FOR XML PATH('')
)
SET @tablename = @schemaname + '.' + @tablename
SET @heading = 'SELECT ''' + right(@heading,len(@heading)-1) + ''' AS CSV, 0 AS Sort' + CHAR(13)
SET @cols = '''"'',' + replace(right(@cols,len(@cols)-1),',', ',''","'',') + ',''"''' + CHAR(13)
IF @header = 'Y'
SET @sqlstrs = 'SELECT CSV FROM (' + CHAR(13) + @heading + ' UNION SELECT CONCAT(' + @cols + ') CSV, 1 AS Sort FROM ' + @tablename + CHAR(13) + ') X ORDER BY Sort, CSV ASC'
ELSE
SET @sqlstrs = 'SELECT CONCAT(' + @cols + ') CSV FROM ' + @tablename
IF @schemaid IS NOT NULL
EXEC(@sqlstrs)
ELSE
PRINT('SCHEMA DOES NOT EXIST')
END
END
GO
--------------------------------------
--EXEC get_csvFormat @schemaname='dbo', @tablename='TradeUnion', @header='Y'