Assuming that if your table has multiple rows, you want multiple rows, you could do something like this. Note that all your values will be implicitly converted to a varchar
or nvarchar
, and so you are are allowing SQL Server to determine what it'll be.
Assuming you're on a recent version of SQL Server you can do this (if not, you'll need to use the old FOR XML PATH
method for STRING_AGG
and CONCAT
for CONCAT_WS
(and STUFF
with both):
DECLARE @SchemaName sysname = N'YourSchema',
@TableName sysname = N'YourTable';
DECLARE @SQL nvarchar(MAX),
@CRLF nchar(2) = NCHAR(13) + NCHAR(10);
DECLARE @SQL nvarchar(MAX),
@CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SELECT @SQL = N'SELECT CONCAT_WS('','',' + STRING_AGG(QUOTENAME(c.[name]),',') WITHIN GROUP (ORDER BY c.column_id) + N') AS YourColumns' + @CRLF +
N'FROM ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName) + N';'
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
WHERE s.[name] = @SchemaName
AND t.[name] = @TableName
--PRINT @SQL; --Your best friend;
EXEC sys.sp_executesql @SQL;