/* SPLIT A STRING BASED ON A DELIMITER AND RETURN THE FRAGMENT AT A SPECIFIED POSITION */
/* =============================================================================================================== */
DROP FUNCTION IF EXISTS SPLIT_STRING;
COMMIT;

DELIMITER //

CREATE FUNCTION `SPLIT_STRING`(`p_string` text, `p_delimiter` varchar(5), `p_position` INTEGER)
RETURNS TEXT
BEGIN

	DECLARE v_string TEXT;
	
	SET v_string = 
		REPLACE(
			SUBSTRING(
				SUBSTRING_INDEX(p_string, p_delimiter, p_position), 
				LENGTH(
					SUBSTRING_INDEX(p_string, p_delimiter, p_position - 1)
				) + 1
			), 
			p_delimiter, 
			''
		);

	IF v_string = '' THEN 
		SET v_string = null;
	END IF;
	
	RETURN v_string;

END 
//
COMMIT //

DELIMITER ;
