INSERT INTO ACADEMIC_SERVICE_REQUEST_YEAR (YEAR) (SELECT DISTINCT(SERVICE_REQUEST_YEAR) FROM ACADEMIC_SERVICE_REQUEST WHERE SERVICE_REQUEST_YEAR NOT IN (SELECT YEAR FROM ACADEMIC_SERVICE_REQUEST_YEAR));
UPDATE ACADEMIC_SERVICE_REQUEST_YEAR SET KEY_ROOT_DOMAIN_OBJECT = 1;
UPDATE ACADEMIC_SERVICE_REQUEST_YEAR SET OID_ROOT_DOMAIN_OBJECT = (SELECT OID FROM ROOT_DOMAIN_OBJECT);
select @xpto:=FF$DOMAIN_CLASS_INFO.DOMAIN_CLASS_ID from FF$DOMAIN_CLASS_INFO where FF$DOMAIN_CLASS_INFO.DOMAIN_CLASS_NAME like '%AcademicServiceRequestYear';
UPDATE ACADEMIC_SERVICE_REQUEST_YEAR SET OID = (@xpto << 32) + ID_INTERNAL;
UPDATE ACADEMIC_SERVICE_REQUEST ACS INNER JOIN ACADEMIC_SERVICE_REQUEST_YEAR ACSY ON ACSY.YEAR = ACS.SERVICE_REQUEST_YEAR SET ACS.KEY_ACADEMIC_SERVICE_REQUEST_YEAR = ACSY.ID_INTERNAL;
UPDATE ACADEMIC_SERVICE_REQUEST ACS INNER JOIN ACADEMIC_SERVICE_REQUEST_YEAR ACSY ON ACSY.YEAR = ACS.SERVICE_REQUEST_YEAR SET ACS.OID_ACADEMIC_SERVICE_REQUEST_YEAR = ACSY.OID;
CREATE TEMPORARY TABLE _TMP_ AS SELECT KEY_ACADEMIC_SERVICE_REQUEST_YEAR, MAX(SERVICE_REQUEST_NUMBER) AS MAX_NUMBER FROM ACADEMIC_SERVICE_REQUEST GROUP BY ACADEMIC_SERVICE_REQUEST.SERVICE_REQUEST_YEAR;
UPDATE ACADEMIC_SERVICE_REQUEST_YEAR INNER JOIN _TMP_ ON ID_INTERNAL = KEY_ACADEMIC_SERVICE_REQUEST_YEAR SET LATEST_SERVICE_REQUEST_NUMBER = MAX_NUMBER;
DROP TABLE _TMP_;