Unconventional Ways To Avoid SQL Recursion
Ken Robertson asks, “Which is better recursion or temp tables?” I would suggest that you don't have to do either. Given Ken's case (calculating the number of nodes in a tree structure for displaying image counts), it is likely that this query is going to run quite often, which means that you don't want to lock up your server to preform recursive operations every time a node is requested. One option is to cache the data somewhere, which is a pretty good option in some cases, but in this case, we want real time results. An unconventional way to avoid this breaks normalization rules slightly, but probably offers the best overall solution compared to some of the more complex ways you can do this (not to mention that it is a heck of a lot easier to code than the alternatives). Add a "path" column to each node. Now, when you run your queries, you can do something like this:
SELECT Count (*) from [Node] inner join [Item] ... Where [Node].[Path] Like (@BasePath+'%')
This could drastically improve the performance of any recursive operations. The only thing you have to make sure to do is update paths if the node is moved:
UPDATE [Node] Set [Path] = @NewPath+RIGHT([Path], len([Path])-len(@OldPath)) WHERE [Path] Like (@OldPath+'%')
Of course, moves are little slower than just changing a FK, but assuming moves don't happen with insanely high frequency, this should be perfectly reasonable (considering the time you save on selects). If you can wait till Yukon, it should have support for recursive queries built in (SQL3 syntax I assume?)...