Back to Papers and Articles | |||||||||||||||||||||||||||||||
Using PostgreSQL User-Defined Functions to solve the Tree Problem Copyright 2004 Paragon Corporation ( February 15, 2004) |
|||||||||||||||||||||||||||||||
UPDATE: This artilce ws written for PostgreSQL 7.4. We have a newer version of this article for PostgreSQL 8.4. Using Recursive Common table expressions to represent Tree structures In this example we will tackle a different recursive example instead of the who reports to who problem that we had in SQL Server article. We leave it up to the reader as an exercise to apply the same apporach to solve the who reports to who problem. The Problem Suppose you are tracking supplies and have a field called si_item and another called si_parentid. The parent keeps track of what subclass a supply item belongs to. E.g. you have paper parent that has subclasses such as recycled, non-recycled. When someone takes supplies, you want to return the fully qualified name e.g. Paper->Recycled->20 Lb Below is what the structure of your table looks like. si_id int, si_parentid int, si_item. In your table are the following entries
Now everyone at work is asked to throw all their paper in the recycle bin for recycling. With recycling, we are told we will save trees and have plentiful amounts of paper. John loves his paper and doesn't want it to be recycled. He surely doesn't want his beautiful paper to get into someone else's hands. So what he does is wrap his paper in styrofoam and throw it in the recycle bin. He thinks (Hee hee - that'll teach them to ask me to give up my paper). Little does John know that there is are other Johns and Janes in the halls thinking the same thing. The function that will display the fully qualified name is below . The function looks as follows
To figure out what paper John will ask for
SELECT cp_getitemfullname(8) As thename
This returns
Paper->Non-Recycled->Scraps
| |||||||||||||||||||||||||||||||
Back to Papers and Articles | |||||||||||||||||||||||||||||||
|