简体   繁体   中英

Insert Line break in Case expression result SQL

I have the following Case expression:

SELECT 
    CASE 
       WHEN item = '662627-4' 
          THEN 'KLX Licensed & BOM CONTAINS KLX LICENSED PART(S)'
          ELSE NULL

The result is as follows:

KLX Licensed & BOM CONTAINS KLX LICENSED PART(S)

I would like to have it display like this on two lines:

KLX Licensed &
BOM CONTAINS KLX LICENSED PART(S)`

Is this possible? Is there a character to insert a carriage return in the case statement?

I'm using SQL Server 2016.

If you are using SSMS: You will not see a difference in the results grid, but you will if you set results to text (shortcut: Ctrl+T).

SELECT CASE WHEN item = '662627-4' THEN 'KLX Licensed & '+char(10)+'BOM CONTAINS KLX LICENSED PART(S)'
           ELSE NULL end

or

SELECT CASE WHEN item = '662627-4' THEN 'KLX Licensed &
BOM CONTAINS KLX LICENSED PART(S)'
           ELSE NULL end

rextester demo: http://rextester.com/YWD92075

Good question.

Comment before we answer it: your code example would not execute, simply because the CASE statement needs to have the END keyword denoting the end of the CASE statement.

As for your question, You can add a carriage return and line feed into your text which would give you a new line. You would not see this in the data-mode in SSMS (when you see the results in tabular form). The data would be stored with the line breaks and would display as such when exported or viewed as text. I personally found that a line feed or carriage return alone would not always do the trick (depending on where you exported this), though the combination worked every time.

Try the following:

SELECT 
    CASE 
       WHEN item = '662627-4' 
          THEN 'KLX Licensed &'+CHAR(10)+CHAR(13)+' BOM CONTAINS KLX LICENSED PART(S)'
          ELSE NULL

I was able to export to Excel, CSV and even import into SSAS all the while maintaining the line breaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM