-- Tables

-- Alters

ALTER TABLE [AKUZ].[T_ACCOMPANYING_DISEASES] ADD [TypeDisease] int NULL
GO
UPDATE [AKUZ].[T_ACCOMPANYING_DISEASES] SET [TypeDisease] = 0
GO
ALTER TABLE [AKUZ].[T_ACCOMPANYING_DISEASES] ALTER COLUMN [TypeDisease] int NOT NULL
GO


declare @table table 
(
	--[AKUZ].[T_ACCOMPANYING_DISEASES](
	[ID] [uniqueidentifier] NULL,

	--[AKUZ].[T_MEDICAL_RECORD](
	[MedicalRecordID] [uniqueidentifier] NULL
)

INSERT INTO @table ([ID], [MedicalRecordID])
SELECT NEWID(), ooi.MedicalRecordID 
FROM AKUZ.T_OUTCOME_OF_INSPECTION ooi
WHERE ooi.MkbComp is NOT NULL

DECLARE @entityID int
SELECT @entityID = EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'ACCOMPANYING_DISEASES'

INSERT INTO AKUZ.T_MEDICAL_RECORD ([MedicalRecordID], [Post], [type_])
	SELECT t.ID, mr.Post, @entityID
	FROM @table t join AKUZ.T_MEDICAL_RECORD mr on t.MedicalRecordID = mr.MedicalRecordID
	
INSERT INTO AKUZ.T_AMBULANCE_CARD_RECORD ([MedicalRecordID], [AmbulanceCard], [AmbulanceEvent], [PostingDate], [PatientBase])
	SELECT t.ID, acr.AmbulanceCard, acr.AmbulanceEvent, acr.PostingDate, acr.PatientBase
	FROM @table t join AKUZ.T_AMBULANCE_CARD_RECORD acr on t.MedicalRecordID = acr.MedicalRecordID

INSERT INTO [AKUZ].[T_OUTCOME_OF_INSPECTION] (MedicalRecordID, ActiveFindDiagnosis, MKBCode, Diagnosis) 
	SELECT t.ID, 0, ooi.MkbComp, ooi.CompDiagnosis
	FROM @table t join AKUZ.[T_OUTCOME_OF_INSPECTION] ooi on t.MedicalRecordID = ooi.MedicalRecordID

INSERT INTO [AKUZ].[T_ACCOMPANYING_DISEASES] (MedicalRecordID, OutcomeOfInspection, TypeDisease) 
	SELECT t.ID, ooi.MedicalRecordID, 1
	FROM @table t join AKUZ.[T_OUTCOME_OF_INSPECTION] ooi on t.MedicalRecordID = ooi.MedicalRecordID


IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[AKUZ].[T_OUTCOME_OF_INSPECTION]') AND name = N'IX_T_OUTCOME_OF_INSPECTION_MkbComp')
	DROP INDEX IX_T_OUTCOME_OF_INSPECTION_MkbComp ON [AKUZ].[T_OUTCOME_OF_INSPECTION] 
GO

ALTER TABLE AKUZ.[T_OUTCOME_OF_INSPECTION] DROP COLUMN MkbComp, CompDiagnosis
GO