Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Using a Recursive CTE to Generate a List


Using a Recursive CTE to Generate a List

Author
Message
smarinova
smarinova
Grasshopper
Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)Grasshopper (14 reputation)

Group: General Forum Members
Points: 14 Visits: 141
Comments posted to this topic are about the item Using a Recursive CTE to Generate a List
Cadavre
Cadavre
SSCrazy
SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)SSCrazy (2.9K reputation)

Group: General Forum Members
Points: 2904 Visits: 8448
Nice article, but was wondering if there was any reason you'd do that over using FOR XML PATH to concatenate a string? I'd imagine that the IO of the recursive CTE must be pretty large, whereas the FOR XML method is likely to be considerably smaller.


Forever trying to learn

For better, quicker answers on T-SQL questions, click on the following...
http://www.sqlservercentral.com/articles/Best+Practices/61537/

For better, quicker answers on SQL Server performance related questions, click on the following...
http://www.sqlservercentral.com/articles/SQLServerCentral/66909/



If you litter your database queries with nolock query hints, are you aware of the side effects?
Try reading a few of these links...

(*) Missing rows with nolock
(*) Allocation order scans with nolock
(*) Consistency issues with nolock
(*) Transient Corruption Errors in SQL Server error log caused by nolock
(*) Dirty reads, read errors, reading rows twice and missing rows with nolock


Craig Wilkinson - Software Engineer
LinkedIn
SQL-DBA
SQL-DBA
SSC-Enthusiastic
SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)

Group: General Forum Members
Points: 153 Visits: 462
Small thing, but I like the first graphic. The title is not cryptic, but you don't know exactly what will follow. 2 seconds after looking at the image, you know. Nice touch.
Jonathan AC Roberts
Jonathan AC Roberts
SSC-Addicted
SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)SSC-Addicted (474 reputation)

Group: General Forum Members
Points: 474 Visits: 1844
A csv list can also be generated using "FOR XML"
I rewrote the final query using this method:

SELECT OfficeID,
(SELECT TOP(1)
C.StateAbbr
FROM dbo.OfficeCounty OC
INNER JOIN dbo.County C
ON C.CountyId = OC.CountyID
WHERE OC.OfficeID = O.OfficeID) AS StateAbbr,
STUFF((SELECT ',' + CountyName
FROM dbo.OfficeCounty OC
INNER JOIN dbo.County C
ON C.CountyId = OC.CountyID
WHERE OC.OfficeID = O.OfficeID
ORDER BY CountyName
FOR XML PATH('')),1,1,'') AS countrynames
FROM dbo.Office O
ORDER BY 2


dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)SSCarpal Tunnel (4.9K reputation)

Group: General Forum Members
Points: 4947 Visits: 6431
Hi Svetlana!

I think this is a nice introductory tutorial on using rCTEs.

However like a couple of folks that have already replied, I'd do it a little differently:


WITH Offices AS (
SELECT a.OfficeID, c.StateAbbr, c.CountyName, c.CountyID
FROM Office a
INNER JOIN OfficeCounty b ON a.OfficeID = b.OfficeID
INNER JOIN County c ON b.CountyID = c.CountyID)
SELECT a.OfficeID, StateAbbr=MAX(StateAbbr)
,countynames=STUFF((
SELECT ', ' + CountyName
FROM Offices b
WHERE a.OfficeID = b.OfficeID
ORDER BY CountyName
FOR XML PATH('')), 1, 2, '')
FROM Offices a
GROUP BY a.OfficeID




I believe that the looping string concatenation you're doing in the rCTE will impact your performance vs. something like the above.

To each his (or her) own I suppose.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
ChrisM@Work
ChrisM@Work
SSChampion
SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)SSChampion (10K reputation)

Group: General Forum Members
Points: 10435 Visits: 19240
Beautifully illustrated, well written and easy to follow. Even though the rCTE method has been shown more than once to be somewhat slower than FOR XML PATH, there are some good ideas here.

I wonder if this method really is faster than a properly-written cursor?
I wonder how it compares to using a quirky update in a function?

“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Exploring Recursive CTEs by Example Dwain Camps
lshanahan
lshanahan
Old Hand
Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)Old Hand (350 reputation)

Group: General Forum Members
Points: 350 Visits: 436
CTEs come in particularly handy for hierarchical views (or table-valued functions if you prefer). I've been working on one app lately part of which allows supervisors to review data entry made by their staff and department heads can see and review everyone in their department, all from the same code just by passing in the id of the person accessing the data. Our organization is small enough performance isn't impacted very much.

Obviously you have to be careful about just how deep your hierarchy goes, etc., but for smallish hierarchical data they are quite nice.

____________
Just my $0.02 from over here in the cheap seats of the peanut gallery - please adjust for inflation and/or your local currency.
animesh.jain
animesh.jain
Forum Newbie
Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)Forum Newbie (1 reputation)

Group: General Forum Members
Points: 1 Visits: 9
We can get the desired output using the following simple Query as well.

SELECT 
O.OFFICEID,
O.STATEABBR,
STUFF((SELECT ',' + CAST(COUNTYNAME AS VARCHAR(8000)) FROM DBO.COUNTY B WHERE O.STATEABBR = B.STATEABBR
FOR XML PATH('')),1,1,'') AS COUNTYNAME
FROM (
SELECT O.OFFICEID,C.STATEABBR, OFF__STATE_COUNT = COUNT(1)
FROM DBO.OFFICE O
INNER JOIN DBO.OFFICECOUNTY OC
ON O.OFFICEID=OC.OFFICEID
INNER JOIN DBO.COUNTY C
ON C.COUNTYID=OC.COUNTYID
GROUP BY O.OFFICEID,C.STATEABBR
) O
ORDER BY O.OFFICEID DESC


Dana Medley
Dana Medley
SSCrazy
SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)SSCrazy (2.4K reputation)

Group: General Forum Members
Points: 2364 Visits: 1691
ChrisM@Work (7/9/2013)
Beautifully illustrated, well written and easy to follow. Even though the rCTE method has been shown more than once to be somewhat slower than FOR XML PATH, there are some good ideas here.

I wonder if this method really is faster than a properly-written cursor?
I wonder how it compares to using a quirky update in a function?


+1 @ChrisM

Thank you for the article. This was a very nice read and I am a big fan of rCTE's. Chris kind of summed up what I wanted to say (although I always forget about the quirky update) Hehe



Everything is awesome!
SQL-DBA
SQL-DBA
SSC-Enthusiastic
SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)SSC-Enthusiastic (153 reputation)

Group: General Forum Members
Points: 153 Visits: 462

Oh no, we're toast! I've got this. *Keyboard clatter* Woah, how'd you do that? I'm a DBA...Booyah

That's great...
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search