Solution to the problem that SQL database query result field contains new line character, which leads to copy to excel dislocation

Problem description:
in the process of work, sometimes encountered such a problem, write a SQL query to query data in the database, see the number of rows (such as 1000 rows), but make a copy of the query results to Excel, but happened mismatch, and lead to Excel in the number of lines is more than 1000 lines, caused the number of rows of data inconsistency.

field value contains char(10) newline character, copy the field value to Excel.
Source:
some corresponding cell contains a newline, lead to dislocation happened in copy to Excel.

Option 1 (Recommended) : Enclose the field values in question in double quotation marks so that the newline characters in the field values are restricted to the correct Excel cell.
scenario 2: use the script to remove the corresponding field value newline character.
create table #t
(
Name nvarchar(50),
Remark nvarchar(50)
)

insert into #t
lues (‘ A1 ‘+ char(10) +’ B1 ‘, ‘row 1’), (‘ A2B2 ‘, ‘row 2’)

select Name, Remark
om #t
— Solution 1: You can put double quotation marks directly in the field, and copy it to Excel without misplacing or showing redundant double quotation marks.
select ‘”‘ + Name + ‘”‘ as Name, Remark
om #t

select replace(replace(Name, char(13), ‘ ‘), char(10), ‘ ‘) as Name, Remark
om #t
drop table #t

Read More: