Creating hierarchy results table in SQL Server 2005?
-
I'm trying to create a list of galleries in parent - child order so the results would come out like Parent Gallery 1 Parent Gallery 1s children Parent Gallery 1s children children Parent Gallery 2 Parent Gallery 2s children Parent Gallery 2s children children and so on Each gallery has an id and parentid, the top level gallery have parentid of 0. What I would like to do is return the id and gallery name for each gallery in the order above. Is it possible to do this using tsql, CLR etc.
-
Answer:
Try the WITH common table expression, perhaps like this: WITH t (name, id, level, path) as (SELECT name, id, 0, cast('\' + name as varchar(MAX)) path FROM galleries WHERE parentid = 0 UNION ALL SELECT g.name, g.id, t.level + 1, t.path + '\' + g.name FROM galleries g inner join t on t.id = g.parentid) select replicate(' ',level) + name Name, path from t order by path The key to this is using a self-join within the WITH common table expression to get the recursion.
Arachne at Yahoo! Answers Visit the source
Related Q & A:
- How to control the excessive use of ram by SQL Server?Best solution by Database Administrators
- Can I create a second filestream container on an existing SQL Server 2008 database without going offline?Best solution by Database Administrators
- How to upgrade sql server express 2005 to 2008R2?Best solution by Server Fault
- How Do I Configure SQL Server 2005 Backend?Best solution by Server Fault
- How to add primary key from multiple table as a foreign key in a table in sql server 2008?Best solution by stackoverflow.com
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.