Sounds like a job for PL/SQL...