2014-08-08 12:55:00
Option 1
Unfortunately, SQL Server does not have an easy function to generate a comma-separated list, you will have to implement FOR XML PATH with the STUFF command to get the list.
For example:
SELECT STUFF((SELECT TOP 3 ', ' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS FOR XML PATH('')), 1, 1, '') COLLATE DATABASE_DEFAULT
This example will return the first three rows from the COLUMNS table, in the following format:
AgencyName, AssetNo, ContractorID
If COLLATE DATABASE_DEFAULT
is used the result may become truncated when using SSMS. Fix this by changing the SSMS setting
Tools | Options... | Query Results | SQL Server | Results to Text | Maximum number of characters displayed in each column: to 8192.
Then restart SSMS.
Option 2
The COALESCE
option only works for variable output.
DECLARE @Names VARCHAR(8000) SELECT TOP 3 @Names = COALESCE(@Names + ', ', '') + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS PRINT @Names
This example will return the first three columns from the COLUMNS table, in the following format:
AgencyName, AssetNo, ContractorID