How to insert a line break in a SQL Server VARCHAR/NVARCHAR string
Look no further! Throw in CHAR(13) + CHAR(10)
and you've got your new line break in SQL Server's VARCHAR
or NVARCHAR
.
Output:
Line 1
Line 2
Check out those line breaks in "Results to Grid" or "Results to Text" view in SSMS.
Meet the ASCII family
In ASCII, our beloved characters CHAR(13)
and CHAR(10)
signify Carriage Return (CR) and Line Feed (LF), respectively. These guys are your ticket to a more readable SQL VARCHAR
.
Let's break some lines
Create a multi-line string by placing a carriage return and line feed where you want a break:
Forget monotonous strings, your SQL text is now a piece of art.
The big reveal
New line breaks don't like to brag. They are hidden in SSMS default settings. But with PRINT
, you can make them the center of attention:
Stored line breaks
Your line breaks can shine in SQL Server Stored Procedures. They make complex queries feel like breeze:
"The train has left the station!" - space issues
Using line breaks mean you're adding two more characters to the party. So, while it makes your SQL text look good, it might increase your storage. Check the effect with LEN()
.
Hands-on applications
Making your report cards.
Line breaks come in handy for enhancing SQL Server reports. Nothing like a well-formatted report to speed things up.
Welcome to the dynamic world
When building strings dynamically, STRING_AGG()
and CONCAT_WS()
can be your partners-in-crime for including line breaks:
Migrating in style
Whether it's importing data into SQL Server or sending data on a vacation (exports), maintaining line breaks is crucial.
Proceed with caution
Line breaks, once popular, are now shunned by front-end applications, making them problematic. Be sure to check compatibility, or risk a meltdown.
Was this article helpful?