Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2002-03-31 : 22:54:38
|
Bob Lynn writes "Suppose you have the following sample table:id parent_id-- ---------5 null10 515 520 525 1030 1035 25 In SQL Server 2000 is it possible to define a query that does the following:"Give me the top level parent for any id."So in this example, I want to construct a query where I feed it id=35 and it returns id=5 (since id=5 is at the top level).I know in Oracle you can use the "connect by prior" statement to define hierarchical relationships ... does SQL Server have anything comparable???Thanks for the help ..." |
|
|
Lavos
Posting Yak Master
200 Posts |
Posted - 2002-04-01 : 08:01:44
|
| Sorry, but SQL Server doesn't have a a function similar to the connect by prior construct.You'll have to use a loop to find the parent, but it's easy to fit it into a stored procedure (I just wrote one just the other day to find all the finished parts a component was used in.)Ken Henderson's Guru's Guide has a good section on this, and Celko's SQL for Smarties has a few interesting approaches (though you'll have to adapt them to SQL Server)My personal favorite (from Ken's book)DECLARE @List TABLE (Lvl int, id int)DECLARE @Lvl intSELECT @Lvl=1INSERT INTO @ListSELECT @Lvl, parent_id FROM YourTable WHERE id=@YourIdWHILE (@@ROWCOUNT > 0)BEGINSELECT @Lvl = @Lvl+1INSERT INTO @ListSELECT @Lvl, parent_id FROM YourTable INNER JOIN @List ON (YourTable.id=@List.id) WHERE Lvl=@Lvl-1ENDSELECT id FROM @List INNER JOIN YourTable ON (YourTable.id=@List.id)WHERE parent_id IS NULL----------------------"O Theos mou! Echo ten labrida en te mou kephale!" |
 |
|
|
|
|
|