Column to CSV

  • scalar valued function that converts given column into comma separated values

The first (intuitive approach)

  • This approach is very intuitive and straightforward, however pretty slow
SELECT @s = isnull(@s + ', ' + CONVERT (VARCHAR(10),NumericValue), CONVERT (VARCHAR(10),NumericValue))
FROM Measurement
ORDER BY ColumnA;

Second approach

SELECT SUBSTRING(
(SELECT ',' + CONVERT (VARCHAR(10),FloatValue)
FROM Measurement
ORDER BY ColumnA
FOR XML PATH('')),2,200000) AS CSV

Experimental Comparison

  • Comparison was performed on cca 40000 float values.
  • You can see that second approach is considerably faster.
-- First approach
SQL Server Execution Times:
   CPU time = 1092 ms,  elapsed time = 1090 ms.
-- Second approach
 SQL Server Execution Times:
   CPU time = 63 ms,  elapsed time = 85 ms.
programming/mssql/columntocsv.txt · Last modified: 2018-06-21 19:48 (external edit)
CC Attribution-Noncommercial-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0