Refactoring common SQL code