Friday 20 February 2015

SQL SERVER – Difference between Line Feed (\n) and Carriage Return (\r) – T-SQL New Line Char


Today, we will examine something very simple and very generic that can apply to hordes of programming languages. Let’s take a common question that is frequently discussed – What is difference between Line Feed (\n) and Carriage Return (\r)?
Prior to continuing with this article let us first look into few synonyms for LF and CR.
Line Feed – LF – \n – 0x0a – 10 (decimal)
Carriage Return – CR – \r – 0x0D – 13 (decimal)
Now that we have understood that we have two different options to get new line, the question that arises is – why is it so?
The reason is simple. Different operating systems have a different way of understanding new line. Mac only understands ‘\r’ as new line, while Unix and Linux understand ‘\n’ as new line character. Our favorite OS windows needs both the characters together to interpret as new line, which is ‘\r\n’. This is the reason why a file created in one OS does not open properly in another OS and makes it messy.
Now, let us see how we can create a new line in SQL Server. It is a very simple script yet very useful when we have to do run print something or generate scripts. I have illustrated two examples below that are very easy to understand. In the first example, there are no new line chars inserted and for the same, everything is displayed in a single line. However, in the second example, new line char is inserted and the lines are separated with a new line.
Example 1: No new line feed char
DECLARE @NewLineChar AS CHAR(2= CHAR(13) + CHAR(10)PRINT ('SELECT FirstLine AS FL SELECT SecondLine AS SL' )GO
Example 2: With new line feed char
DECLARE @NewLineChar AS CHAR(2= CHAR(13) + CHAR(10)PRINT ('SELECT FirstLine AS FL ' +@NewLineChar 'SELECT SecondLine AS SL' )GO
I hope my examples make things more clear to you all. Let me have your feedback on this article.

No comments:

Post a Comment