Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come concatenare tutte le colonne in una selezione con SQL Server

Qualsiasi numero di colonne per un determinato nome di tabella;Se hai bisogno di nomi di colonna avvolto con <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 Esempio qui

-- RESULTS 
<text>col1, col2, col3,...</text>

Se hai bisogno, seleziona la query insieme di risultati avvolto con <text> poi;

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 Esempio qui

--RESULTS
<text>c1r1,c2r1,c3r1,...</text>
<text>c1r2,c2r2,c3r2,...</text>
<text>c1r3,c2r3,c3r3,...</text>