Refactor sql makeprg function