Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use sql for xml path('') but retain carriage returns

Tags:

sql

xml

i have the following piece of code

select
    (
    select cast(Narrative as Varchar(max)) + char(13) 
    from officeclientledger 
    where ptmatter=$matter$ and ptTrans=4 
    for xml path (''), type
    )

which deliver results such as:

Cwm Taff NHS Trust Medical Records ; Dr Purby Medical Records ; (excluding spaces, needed to insert for the purpose of asking the question)

however, is there a way of delivering the results such as

Cwm Taff NHS Trust Medical Records

Dr Purby Medical Records

like image 706
James Parish Avatar asked May 24 '11 16:05

James Parish


People also ask

How does SQL handle carriage return?

In SQL Server, we can use the CHAR function with ASCII number code. We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return.

How do I insert a carriage return in SQL query?

Inserting carriage return is similar to line break. You just need to replace CHAR(10) with CHAR(13). Here is the example.

Can you use SQL in XML?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.

What does for XML Path do in SQL?

We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.


2 Answers

This can't be done using the results to grid functionality in SSMS. However, if you use the results to text option and replace your CHAR(13) with CHAR(10), you'll get the desired results.

like image 76
James Hill Avatar answered Nov 14 '22 22:11

James Hill


I am hitting the same problem and i can't use Char(10) because the receiving system expect Char (13). So I used below query to replace the value in my result and it worked.

SELECT Coloumn = REPLACE(@v_Get_UPC_List, '
', CHAR(13)) 
like image 42
Mani Avatar answered Nov 14 '22 23:11

Mani