Search Suggest

SQL Server, Concatenates text from multiple rows into a single string!

Hi guys, 


Today we take a little break, just a little post for a useful super tip!
 
Today a colleague of mine had developed a function that used a CTE to do what today I will show you can be done with a single line of SQL code. Needless to say, everything was extremely slow.
 
Enjoy the reading of this supertip!

Concatenates text from multiple rows into a single string

Suppose you have an order or an invoice with a variable number of rows.
Think of the Ordtes and OrdRig tables that we have used in so many examples in this blog.

We extract the data of an order with this command:

SELECT id, idordtes, Descr FROM ordrig WHERE IdOrdtes = 33

...the data:
 
 
 
Suppose we need to have all descriptions on the same row.
How to do it without cursor ore CTE?


Simple! 


DECLARE @Names VARCHAR(8000)
SELECT @Names = ISNULL(@Names,'') + ' ' + Descr FROM ordrig WHERE IDordtes = 33
SELECT @Names

 
Trying this you will get:



et voilà!


Of course you can order your data:

DECLARE @Names VARCHAR(8000)
SELECT @Names = ISNULL(@Names,'') + ' ' + Descr FROM ordrig WHERE IDordtes = 33 ORDER BY DESC
SELECT @Names

 



How much does this operation cost? Little

 From the point of view of the pages read, nothing changes.

Table 'ORDRIG'. Scan count 1, logical reads 11, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'ORDRIG'. Scan count 1, logical reads 11, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 
From the point of view of the execution plan only a compute scalar operator is added.
The total cost is however little compared to the execution of a cycle for example with a cursor





See you soon and I hope you enjoyed reading this post.
Next time we will talk about SQL2019 and the news it brings us
 
Luca
 
Luca Biondi @ SQLServerPerformance blog!

 






Next post:

Previous post: What's New in SQL Server 2019 and Table Variables deferred compilation

Post a Comment