Let\'s say you have the following table:
items(item_id, item_parent)
... and it is a self-referencing table - item_parent r
If the database is SQL 2005 / 2008 then...
The easiest way to get this is using a CTE (Common Table Expression) that is designed to recurse.
WITH myCTE (Item_id, Depth)
AS
(
Select Item_ID, 0 as Depth From yourTable where Item_Parent=0
Union ALL
Select yourTable.Item_ID, Depth + 1
From yourTable
inner join myCte on yourTable.item_Parent = myCte.Item_Id
)
Select Item_id, Depth from myCTE
The output is as follows:
Item_Id Depth
1 0
2 0
3 1
4 1
5 2
From that you can format it as you wish.