Moved SQL to stored functions.
Changed SQL to new coding notation.