Depending on what database server use, this functionality may be provided for you already. Otherwise you can create a function that call itself to return this information, or implement a Materialized Path solution.
Update:
For DB2 you can make use of Recursive Common Table Expressions.