
INSERT INTO AKUZ.T_MEDICAL_EPISODE (MedicalEpisodeID, TNMS, SetDTClinicalDiagnosis, OutcomeRecord, AmbulanceEvent, PaymentType, Mkb, Diagnosis, Descr, type_)
SELECT MedicalExaminationDataID, TNMS, SetDTClinicalDiagnosis, OutcomeRecord, AmbulanceEvent, PaymentType, Mkb, Diagnosis, Descr, 
(SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'MEDICAL_EXAMINATION_DATA' and e.Schema = 'AKUZ' limit 1)
FROM AKUZ.T_MEDICAL_EXAMINATION_DATA;

ALTER TABLE AKUZ.T_MEDICAL_EXAMINATION_DATA RENAME COLUMN MedicalExaminationDataID TO MedicalEpisodeID;

ALTER TABLE AKUZ.T_MEDICAL_EXAMINATION_DATA ADD CONSTRAINT FK_T_MEDICAL_EPISODE_T_MEDICAL_EXAMINATION_DATA_Medica_55EF7917
FOREIGN KEY("medicalepisodeid") REFERENCES AKUZ.T_MEDICAL_EPISODE (MedicalEpisodeID);




ALTER TABLE AKUZ.T_DIVISION_SIGNIFICANT_EVENTS ALTER COLUMN MovementsDivisionCard DROP NOT NULL;

INSERT INTO AKUZ.T_DIVISION_SIGNIFICANT_EVENTS (DivisionSignificantEventsID, PostingDate, Post, MedicalEpisode, type_)
SELECT ChangeDiagnosisInPolyclinicEventID, PostingDate, Post, MedicalExaminationData, 
(SELECT e.EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'CHANGE_DIAGNOSIS_IN_POLYCLINIC_EVENT' and e.Schema = 'AKUZ' limit 1)
FROM AKUZ.T_CHANGE_DIAGNOSIS_IN_POLYCLINIC_EVENT;

ALTER TABLE AKUZ.T_CHANGE_DIAGNOSIS_IN_POLYCLINIC_EVENT RENAME COLUMN ChangeDiagnosisInPolyclinicEventID TO DivisionSignificantEventsID;

ALTER TABLE AKUZ.T_CHANGE_DIAGNOSIS_IN_POLYCLINIC_EVENT ADD CONSTRAINT FK_T_DIVISION_SIGNIFICANT_EVENTS_T_CHANGE_DIAGNOSIS_IN_04FFE038
FOREIGN KEY("divisionsignificanteventsid") REFERENCES AKUZ.T_DIVISION_SIGNIFICANT_EVENTS (DivisionSignificantEventsID);



UPDATE AKUZ.T_NURSE_MEDICAL_EXAMINATION
SET MedicalEpisode = MedicalExaminationData;



ALTER TABLE AKUZ.T_ASSOCIATED_AND_COMPLICATION_DISEASE ALTER COLUMN MedicalExaminationData DROP NOT NULL;

UPDATE AKUZ.T_ASSOCIATED_AND_COMPLICATION_DISEASE
SET MedicalEpisode = MedicalExaminationData;



ALTER TABLE AKUZ.T_POST_TREAT ALTER COLUMN MovementsDivisionCard DROP NOT NULL;

INSERT INTO AKUZ.T_POST_TREAT (PostTreatID, BeginCareDate, Post, MedicalEpisode)
SELECT NEWID(), PostingDate, Post, MedicalEpisodeID
FROM AKUZ.T_MEDICAL_EXAMINATION_DATA;
