DROP PROCEDURE IF EXISTS AddColumnUnlessExists;

DELIMITER $$
CREATE PROCEDURE AddColumnUnlessExists(IN tabela tinytext, IN coluna tinytext, IN tipo tinytext)
BEGIN
    IF NOT EXISTS (
		SELECT * FROM information_schema.COLUMNS
		WHERE column_name=coluna
		and table_name=tabela
		and table_schema=DATABASE()
		)
	THEN
		set @ddl=CONCAT('ALTER TABLE ',DATABASE(),'.',tabela,
			' ADD COLUMN ',coluna,' ',tipo);
		prepare stmt from @ddl;
		execute stmt;
	END IF;
END $$
DELIMITER ;



DROP FUNCTION IF EXISTS ExtractNumber;


DELIMITER $$

CREATE FUNCTION `ExtractNumber`(in_string VARCHAR(50)) 
RETURNS INT
NO SQL
BEGIN
    DECLARE ctrNumber VARCHAR(200);
    DECLARE finNumber VARCHAR(200) DEFAULT '';
    DECLARE sChar VARCHAR(1);
    DECLARE inti INTEGER DEFAULT 1;

    IF LENGTH(in_string) > 0 THEN
        WHILE(inti <= LENGTH(in_string)) DO
            SET sChar = SUBSTRING(in_string, inti, 1);
            SET ctrNumber = FIND_IN_SET(sChar, '0,1,2,3,4,5,6,7,8,9'); 
            IF ctrNumber > 0 THEN
                SET finNumber = CONCAT(finNumber, sChar);
            END IF;
            SET inti = inti + 1;
        END WHILE;
        RETURN CAST(finNumber AS UNSIGNED);
    ELSE
        RETURN 0;
    END IF;    
END$$

DELIMITER ;
