To me, it sounds like a perfect place for a stored procedure.