/* STORED FUNCTIONS */
/* Don't forget to GRANT EXECUTE ON CWZ.* TO 'cwz'@'%' */

DELIMITER $$
	
CREATE FUNCTION FMT(val DOUBLE) RETURNS varchar(32) DETERMINISTIC NO SQL
BEGIN
	RETURN CONCAT('$', FORMAT(val, 2));
END $$
	
CREATE FUNCTION ABBV(num DOUBLE) RETURNS varchar(16) DETERMINISTIC NO SQL
BEGIN
   DECLARE fnum varchar(16);
    
   IF num >= 0 AND num < 1000 THEN
    	SET fnum = CONCAT('$', FORMAT(num, 0));
   ELSEIF num >= 1000 AND num < 1000000 THEN
   	SET fnum = CONCAT('$', FORMAT(num DIV 1000, 0), "K");
   ELSEIF num >= 1000000 AND num < 1000000000 THEN
      SET fnum = CONCAT('$', FORMAT(num DIV 1000000, 0), "M");
   ELSEIF num >= 1000000000 AND num < 1000000000000 THEN
      SET fnum = CONCAT('$', FORMAT(num / 1000000000, 1), "B");
   ELSEIF num >= 1000000000000 THEN
      SET fnum = CONCAT('$', FORMAT(num / 1000000000000, 2), "T");
   ELSE
    	SET fnum = "###";
   END IF;
    
   RETURN fnum;
END $$

DELIMITER ;