DROP PROCEDURE IF EXISTS `sp_setTaxMaster`;

DELIMITER //

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_setTaxMaster`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
	BLOCK1: BEGIN
		DECLARE DONE_BLOCK1 INT DEFAULT 0;
		DECLARE CompanyID INT;
		DECLARE CURSOR_CompanyID CURSOR FOR
			SELECT
				company.ID
			FROM
				company
			WHERE
				company.is_delete = 0;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET DONE_BLOCK1 = 1;
		
		OPEN CURSOR_CompanyID;
		REPEAT
		FETCH CURSOR_CompanyID INTO CompanyID;
		
		IF NOT EXISTS(SELECT tax_master.ID FROM tax_master WHERE tax_master.companyID = CompanyID) THEN
			INSERT INTO tax_master (
				companyID,
				code,
				name,
				taxType,
				taxPercentage,
				taxClass,
				taxGroup,
				description,
				taxAccount,
				`status`,
				createdBy
			)
			SELECT
				CompanyID,
				_ref_tax_master.code,
				_ref_tax_master.name,
				_ref_tax_master.taxType,
				_ref_tax_master.taxPercentage,
				_ref_tax_master.taxClass,
				_ref_tax_master.taxGroup,
				_ref_tax_master.description,
				NULL,
				0,
				0
			FROM _ref_tax_master;
		END IF;

		UNTIL DONE_BLOCK1 END REPEAT;
		CLOSE CURSOR_CompanyID;
	END BLOCK1;
END

//