68
votes

I recently upgraded to SQL2012 and am using Management Studio. One of my columns in the database has a CHAR(13) + CHAR(10) stored in it.

When I was using SQL Server 2008, this would copy and paste completely fine into Excel. Now, however, copying and pasting the same data creates a new line/ carriage return in the data I have in Excel.

Is there a setting I missed in SQL2012 that will resolve this issue? I don't want to simply REPLACE(CHAR(13) + CHAR(10)) on every single database selection, as I would have to go from using SELECT * to defining each individual column.

19
So you're saying you don't want the carriage return to show up in excel, despite it being in the data? It sounds like they simply fixed a bug from 2008 to 2012 if that's the case...if that's how your data is represented you need to manipulate it to the format you want instead - Derek Kromm
The CSV format is very specific, and accounts for all possible characters by requiring strings with quotes, commas, or line breaks to be enclosing in double quotes, with actual double quotes doubled. SSMS 2012 (and 2008) just throws everything in a file and sticks commas between cells, utterly sloppy and useless. Whatever format 2012 is putting on the clipboard is very very wrong, unlike SSMS 2008. - Triynko
There is an option under Tools > Options > Query Results > Results To Grid > "Quote strings containing list separators when saving .csv results". It's nonsense that this option is unchecked by default, in other words a complete violation of the CSV file format. - Triynko
LOL, even WORSE... with that option checked, instead of turning double quotes into pairs of double quotes like the CSV specification says, it converts double quotes into two single quotes. This is utterly, completely unacceptable. - Triynko
Someone already filed a bug report about this here: connect.microsoft.com/SQLServer/feedback/details/783274/… Definitely a bug with SSMS 2012. I added a workaround saying just use SSMS 2008 and complained about the poor CSV implementation. - Triynko

19 Answers

55
votes

My best guess is that this is not a bug, but a feature of Sql 2012. ;-) In other contexts, you'd be happy to retain your cr-lf's, like when copying a big chunk of text. It's just that it doesn't work well in your situation.

You could always strip them out in your select. This would make your query for as you intend in both versions:

select REPLACE(col, CHAR(13) + CHAR(10), ', ') from table
40
votes

This is fixed by adding a new option Retain CR\LF on copy or save under the Tools -> Options... menu, Query Results -> SQL Server -> Results to Grid.

You need to open new session (window) to make the change take a place.

The default is unselected (false) which means that copying/saving from the grid will copy the text as it is displayed (with CR\LF replaced with spaces). If set to true the text will be copied/saved from the grid as it actually is stored - without the character replacement.

In case people missed following the chain of connect items (leading to https://connect.microsoft.com/SQLServer/feedback/details/735714), this issue has been fixed in the preview version of SSMS.

You can download this for free from https://msdn.microsoft.com/library/mt238290.aspx, it is a standalone download so does not need the full SQL media anymore.

(Note - the page at https://msdn.microsoft.com/library/ms190078.aspx currently isn't updated with this information. I'm following up on this so it should reflect the new option soon)

28
votes

I found a workaround for the problem; instead of copy-pasting by hand, use Excel to connect to your database and import the complete table. Then remove the data you are not interested in.

Here are the steps (for Excel 2010)

  1. Go to menu Data > Get external data: From other sources > From SQL Server
  2. Type the sql server name (and credentials if you don't have Windows authentication on your server) and connect.
  3. Select the database and table that contains the data with the newlines and click 'Finish'.
  4. Select the destination worksheet and click 'Ok'.

Excel will now import the complete table with the newlines intact.

14
votes

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;
6
votes

@AHiggins's suggestion worked well for me:

REPLACE(REPLACE(REPLACE(B.Address, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ')
4
votes

Line Split Issues when Copying Data from SQL Server to Excel. see below example and try using replace some characters.

SELECT replace(replace(CountyCode, char(10), ''), char(13), '') 
FROM [MSSQLTipsDemo].[dbo].[CountryInfo]
3
votes

This sometimes happens with Excel when you've recently used "Text to Columns."

Try exiting out of excel, reopening, and pasting again. That usually works for me, but I've heard you sometimes have to restart your computer altogether.

3
votes

Seeing as this isn't already mentioned here and it's how I got around the issue...

Right click the target database and choose Tasks > Export data and follow that through. One of the destinations on the 'Choose a destination' screen is Microsoft Excel and there's a step that will accept your query.

It's the SQL Server Import and Export wizard. It's a lot more long-winded than the simple Copy with headers option that I normally use but, save jumping through a lot more hoops, when you have a lot of data to get into excel it's a worthy option.

1
votes

The following "work-around" retains the CRLF and supports pasting data with CRLF characters into Excel without breaking column data into multiple lines. It will require replacing "select *" with named columns and any double-quotes in the data will be replaced with the delimiter value.

declare @delimiter char(1)
set @delimiter = '|'

declare @double_quote char(1)
set @double_quote = '"'

declare @text varchar(255)
set @text = 'This
"is"
a
test'

-- This query demonstrates the problem.  Execute the query and then copy/paste into Excel.
SELECT @text

-- This query demonstrates the solution.
SELECT @double_quote + REPLACE(@text, @double_quote, @delimiter) + @double_quote
1
votes

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

1
votes

One less than ideal workaround is to use the 2008 GUI against the 2012 database for copying query results. Some functionality like "script table as CREATE" does not work, but you can run queries and copy paste the results into Excel etc from a 2012 database with no issues.

Microsoft needs to fix this!

1
votes

Instead of copying & pasting into excel you could export to Excel. Right click the database -> Tasks -> Export Data...

  • Source: SQL Server Native Client
  • Destination: Excel
  • Specify Table Copy or Query: pick query and enter your query

CR/LF retained in the data.

BONUS(nulls are not copied as 'NULL').

1
votes

As many times I have to copy data from SQL to excel, I've created function to deal with with new line and also tab characters (which make shifts in columns after pasting to Excel).

CREATE FUNCTION XLS(@String NVARCHAR(MAX) )

RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @String = REPLACE (@String, CHAR(9), ' ')
    SET @String = REPLACE (@String, CHAR(10), ' ')
    SET @String = REPLACE (@String, CHAR(13), ' ')
    RETURN @String
END

CREATE FUNCTION XLS(@String NVARCHAR(MAX) )
RETURNS NVARCHAR(MAX)

AS
BEGIN
    SET @String = REPLACE (@String, CHAR(9), ' ')
    SET @String = REPLACE (@String, CHAR(10), ' ')
    SET @String = REPLACE (@String, CHAR(13), ' ')
    RETURN @String
END

Example usage:

SELECT dbo.XLS(Description) FROM Server_Inventory
0
votes

You could try save the query results as excel, change the file extension to .txt. Open using excel (open with...) then use text to columns (formatting as text). Not sure if this will work for this situation, but works well for other formatting issues that excel auto-strips off.

0
votes

you really could find out which rows / data has carriage returns and fix the source data.. instead of just put a bandaid on it.

UPDATE table Set Field = Replace(Replace(Field, CHAR(10), ' '), CHAR(13), ' ') WHERE Field like '%' + CHAR(10) + '%' or Field like '%' + CHAR(13) + '%'

0
votes
  • If your table contains an nvarchar(max) field move that field to the bottom of your table.
  • In the event the field type is different to nvarchar(max), then identify the offending field or fields and use this same technique.
  • Save It.
  • Reselect the Table in SQL.
  • If you cant save without an alter you can temporarily turn of relevant warnings in TOOLS | OPTIONS. This method carries no risk.
  • Copy and Paste the SQL GRID display with Headers to Excel.
  • The data may still exhibit a carriage return but at least your data is all on the same row.
  • Then select all row records and do a custom sort on the ID column.
  • All of your records should now be intact and consecutive.
0
votes

I ran into the same issue. I was able to get my results to a CSV using the following solution:

  1. Execute query
  2. Right click in the top left corner of the results grid
  3. Select "Save Results as.."
  4. Choose csv and viola!
0
votes

Changing all my queries because Studio changed version isn't an option. Tried the preferences mentioned above to no effect. It didn't put the quotes in when there was a CR-LF. Perhaps it only triggers when a comma happens.

Copy-paste to Excel is a mainstay of SQL server. Mircosoft either needs a checkbox to revert back to 2008 behavior or they need to enhance the clipboard transfer to Excel such that ONE ROW EQUALS ONE ROW.

-2
votes

Once Data is exported to excel, highlight the date column and format to fit your needs or use the custom field. Worked for me like a charm!