What database are you using? Many databases will allow you to create functions which you could call as part of your SQL code.