generate sql function improvement