Poor Man's Recursion
From: Christian Gustafson (cgustafson_at_gmail.com)
Date: 09/24/04
- Next message: Ed: "Hierarchy"
- Previous message: Mark Ayliffe: "Performance: Query optimizer producing sub-optimal result?"
- Next in thread: Jacco Schalkwijk: "Re: Poor Man's Recursion"
- Reply: Jacco Schalkwijk: "Re: Poor Man's Recursion"
- Reply: David Portas: "RE: Poor Man's Recursion"
- Messages sorted by: [ date ] [ thread ]
Date: 24 Sep 2004 09:15:05 -0700
We use a lot of comma-delimited lists of integers to represent sets of
rows and IDs in SQL Server, since we can't use arrays, etc. for this.
The problem is that it can be a pain to select a set of these values
from several rows and then concatenate them into a single value.
I've found an elegant way to do this, which I call "Poor Man's
Recursion", but I'm not quite sure how and why this works. Can
someone from the MS SQL team confirm that this is the correct behavior
for the query engine, and that this won't disappear in future
releases? Check it out.
Example using pubsdb:
-- use pubs declare @jobList as varchar(4000) select @jobList = isnull(@jobList + ',' + cast(j.job_id as varchar(12)), cast(j.job_id as varchar(12))) from ( select distinct job_id, job_desc from jobs ) as j order by j.job_desc select @joblist as 'JobIDs' JobIDs -------------------------------- 9,3,2,4,14,12,6,7,1,11,10,8,5,13 (1 row(s) affected) A very powerful technique, IMO, if you have ever had to use a cursor to do this. Now you have a comma-delimited list of IDs that we can use as a set and pass into other sprocs, table-based UDFs, trees, etc. Please let me know if this is Kosher T-SQL or an unexpected result. thanks! Christian Gustafson Seattle, WA
- Next message: Ed: "Hierarchy"
- Previous message: Mark Ayliffe: "Performance: Query optimizer producing sub-optimal result?"
- Next in thread: Jacco Schalkwijk: "Re: Poor Man's Recursion"
- Reply: Jacco Schalkwijk: "Re: Poor Man's Recursion"
- Reply: David Portas: "RE: Poor Man's Recursion"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|