[sql] New Line Issue when copying data from SQL Server 2012 to Excel

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.

This question is related to sql sql-server-2008 excel copy-paste sql-server-2012

The answer is


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.


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

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]

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!


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

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').


  • 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.

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.


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

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) + '%'


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.


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.


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!

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!


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.


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;

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.


@AHiggins's suggestion worked well for me:

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

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)


Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to excel

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Converting unix time into date-time via excel How to increment a letter N times per iteration and store in an array? 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to import an Excel file into SQL Server? Copy filtered data to another sheet using VBA Better way to find last used row Could pandas use column as index? Check if a value is in an array or not with Excel VBA How to sort dates from Oldest to Newest in Excel?

Examples related to copy-paste

Copy Paste Values only( xlPasteValues ) HTML page disable copy/paste VBA copy rows that meet criteria to another sheet How to Copy Text to Clip Board in Android? Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table vi/vim editor, copy a block (not usual action) New Line Issue when copying data from SQL Server 2012 to Excel jQuery bind to Paste Event, how to get the content of the paste How to paste text to end of every line? Sublime 2 copy all files and folders from one drive to another drive using DOS (command prompt)

Examples related to sql-server-2012

Count the Number of Tables in a SQL Server Database SQL Server IF EXISTS THEN 1 ELSE 2 Get last 30 day records from today date in SQL Server No process is on the other end of the pipe (SQL Server 2012) How to subtract 30 days from the current date using SQL Server Possible to restore a backup of SQL Server 2014 on SQL Server 2012? SQL Server: Best way to concatenate multiple columns? SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN' SSIS Excel Connection Manager failed to Connect to the Source Sql server - log is full due to ACTIVE_TRANSACTION