DROP PROCEDURE IF EXISTS dump_image;
DELIMITER //
  CREATE PROCEDURE dump_image()
  BEGIN

	DECLARE done INT;
	DECLARE this_id INT;
	DECLARE cur1 CURSOR FOR SELECT DMD_DATA_ID FROM OH_DICOM WHERE DMD_DATA_ID IS NOT NULL;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
	OPEN cur1;
	  read_loop: LOOP
		FETCH cur1 INTO this_id;
		IF done = 1 THEN
			LEAVE read_loop;
		END IF;
		SET @QUERY = CONCAT('SELECT DMD_DATA FROM OH_DICOM_DATA WHERE DMD_DATA_ID=', this_id, ' INTO DUMPFILE "OH_PATH_SUBSTITUTE/DATA_DIR', this_id,'.png"');
		PREPARE WRITE_FILE FROM @QUERY;
		EXECUTE WRITE_FILE;
	  END LOOP;
	CLOSE cur1;
  END //
DELIMITER ;

CALL dump_image();
