Moved some of the SQL that was in code into a stored procedure.