sql func refactor