Any number of columns for a given table name ; If you need column names wrapped in <text>
DECLARE @s VARCHAR(500) SELECT @s = ISNULL(@s+', ','') + c.name FROM sys.all_columns c join sys.tables t ON c.object_id = t.object_id WHERE t.name = 'YourTableName' SELECT '<text>' + @s + '</text>'
SQL Fiddle Example here
-- RESULTS <text>col1, col2, col3,...</text>
If you need to select a result set with <text> , then
SELECT @S = ISNULL( @S+ ')' +'+'',''+ ','') + 'convert(varchar(50), ' + c.name FROM sys.all_columns c join sys.tables t ON c.object_id = t.object_id WHERE t.name = 'YourTableName' EXEC( 'SELECT ''<text>''+' + @s + ')+' + '''</text>'' FROM YourTableName')
SQL Fiddle Example here
--RESULTS <text>c1r1,c2r1,c3r1,...</text> <text>c1r2,c2r2,c3r2,...</text> <text>c1r3,c2r3,c3r3,...</text>
source share