I come across this issue quite often so I thought I would share my solution. For example it's quite a good solution for quick ad-hoc data extracts.
There are many ways to do this but the most performant way is actually the simplest too.
The most common approach which most people fall back to would be to iterate through the collection using a Cursor and format a string that way. For many reasons this is not a good idea, from memory to potential deadlock issues to name 2.
For this demo im going to comma deliminate all my tables into a single column for me to then copy this value straight into my favorite text editor to then save as a CSV.
My data looks like the following.
ProductReview
StoreEventPage
AuditLog
Author
TimeLine
TimeLineEvent
Now using the gist below. I can combine the result set of these string values and concatinate them to one string variable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GO | |
DECLARE @tableName VARCHAR(MAX) | |
SELECT @tableName = COALESCE(@tableName + ',' ,'') + Name | |
FROM sys.tables | |
SELECT @tableName | |
GO |
The end result is the following which we can now save as a csv.
ProductReview,StoreEventPage,AuditLog,Author,TimeLine,TimeLineEvent
Thanks for reading. Always appreciate hearing your thoughts and comments.
Checkout my website for further info and contact details.
But will this work to concatenate a field from many rows into one field in a result set? The example give is useless for adaptation to pretty much any other use.
ReplyDeletethanks for your response brent. Its not suppose to do anything other than return a single column of CSVs. As is it now it wouldnt work combined with any additional data retrieval operations. Im hoping the title of the post will be picked up by someone searching for this quick win. thanks again
Delete