The best way I've come up to include the carriage returns/line breaks in the result (Copy/Copy with Headers/Save Results As) for copying to Excel is to add the double quotes in the SELECT
, e.g.:
SELECT '"' + ColumnName + '"' AS ColumnName FROM TableName;
If the column data itself can contain double quotes, they can be escaped by 'double-double quoting':
SELECT '"' + REPLACE(ColumnName, '"', '""') + '"' AS ColumnName FROM TableName;
Empty column data will show up as just 2 double quotes in SQL Management Studio, but copying to Excel will result in an empty cell. NULL
values will be kept, but that can be changed by using CONCAT('"', ColumnName, '"')
or COALESCE(ColumnName, '')
.
As commented by @JohnLBevan, escaping column data can also be done using the built-in function QUOTENAME
:
SELECT QUOTENAME(ColumnName, '"') AS ColumnName FROM TableName;