8

This seems simple...

How do you store a multi-line string so your code stays nicely formatted.

Doing this is ugly

DECLARE @myStr NVARCHAR(MAX)
SET @myStr = 'This represents a really long
string that i need multiple lines for,
dude.'

but the above results in the correct string output:

SELECT @myStr
'This represents a really long string that i need multiple lines for, dude.'

Doing this makes it easier to read my code:

DECLARE @myStr NVARCHAR(MAX)
SET @myStr = 'This represents a really long
    string that i need multiple lines for,
    dude.'

but results in this:

SELECT @myStr
'This represents a really long     string that i need multiple lines for, 
dude.'

Is there some special way to escape tabs in a multiline string (like every other language has)..

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jamie Marshall
  • 1,885
  • 3
  • 27
  • 50

1 Answers1

13

You're looking for a backslash ("\"):

SET @myStr = 'This represents a really long \
    string that i need multiple lines for, \
    dude.'
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Actually your example gives 2 spaces between 'long' and 'string' - you need to remove the space before the `\`. – Dale K Jan 23 '19 at 22:15
  • And unfortunately it doesn't work if you use spaces instead of tabs - unless its a single space - which doesn't really achieve the desired effect :( – Dale K Jan 23 '19 at 22:16
  • hmm, i'm not getting the desired effect. `'\'` seems to escape the line break, but no the indent at the front of the second line in the string. – Jamie Marshall Jan 23 '19 at 22:35
  • 2
    Hmmm - I was afraid you might have had the *opposite* problem. Plan B is to [concatenate](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/string-concatenation-transact-sql?view=sql-server-2017) your strings: `line 1 ' + 'line 2' + ...` Please let us know if that helps. One other note (if you want to add or retain linefeeds in your text string): https://stackoverflow.com/questions/36608252/ – paulsm4 Jan 23 '19 at 23:09
  • @JamieMarshall it does remove the first tab on the new line, if you are using the tab character. – Dale K Jan 24 '19 at 00:34
  • @DaleBurrell maybe its because I tested putting the whole thing in an indented block? – Jamie Marshall Jan 24 '19 at 02:24
  • Q1) How exactly do you *want* it to look? One continuous line, with no extraneous spacing? Q2) How does it appear using "\" (continuation lines), with the extraneous left-spacing on each line? Q3) Does it appear differently if each continued line is flush-left? Q4) Did you try "+" (concatentation)? Any difference? Q5) How are you displaying it? With a SQL "select" in SSMS? With a console-mode C# app? Other? – paulsm4 Jan 24 '19 at 02:48