
-- Осложнения

declare @table table 
(
	[ID] [uniqueidentifier] NULL,

	[MovementResult] [uniqueidentifier] NULL,

	[Post] [uniqueidentifier] NULL,
	[RecordDate] [datetime] NULL,
	[RecordTime] [datetime] NULL,

	[AmbulanceEvent] [uniqueidentifier] NULL,
	[AmbulanceCard] [uniqueidentifier] NULL,
	[PatientBase] [uniqueidentifier] NULL,
	[PostingDate] [datetime] NULL,

	[Mkb] [varchar](8) NULL,
	[Diagnosis] [varchar](max) NULL,

	[ActiveFindDiagnosis] [bit] NULL
)

INSERT INTO @table ([ID], [MovementResult], [Post], [RecordDate], [RecordTime], [AmbulanceEvent], [AmbulanceCard], [PatientBase], [PostingDate], [Mkb], [Diagnosis], [ActiveFindDiagnosis])
SELECT NEWID(), mres.MedicalRecordID, mr.Post, mr.RecordDate, mr.RecordTime, acr.AmbulanceEvent, acr.AmbulanceCard, acr.PatientBase, acr.PostingDate, mres.MkbAggravation, mres.DiagAggravation, ooi.ActiveFindDiagnosis
FROM AKUZ.T_MOVEMENT_RESULT mres 
JOIN AKUZ.T_MEDICAL_RECORD mr on mres.MedicalRecordID = mr.MedicalRecordID
JOIN AKUZ.T_AMBULANCE_CARD_RECORD acr on mres.MedicalRecordID = acr.MedicalRecordID
JOIN AKUZ.T_OUTCOME_OF_INSPECTION ooi on mres.MedicalRecordID = ooi.MedicalRecordID
WHERE MkbAggravation is not null

DECLARE @newEntityID int
SELECT @newEntityID = EntityID FROM VCLib.T_ENTITIES e WHERE e.EntName = 'ACCOMPANYING_DISEASES' and e.[Schema] = 'AKUZ'

INSERT INTO AKUZ.T_MEDICAL_RECORD ([MedicalRecordID], [Post], [type_], [RecordDate], [RecordTime])
	SELECT t.ID, t.Post, @newEntityID, t.RecordDate, t.RecordTime
	FROM @table t
	
INSERT INTO AKUZ.T_AMBULANCE_CARD_RECORD ([MedicalRecordID], [AmbulanceCard], [AmbulanceEvent], [PostingDate], [PatientBase])
	SELECT t.ID, t.AmbulanceCard, t.AmbulanceEvent, t.PostingDate, t.PatientBase
	FROM @table t 

INSERT INTO [AKUZ].[T_OUTCOME_OF_INSPECTION] (MedicalRecordID, ActiveFindDiagnosis, MKBCode, Diagnosis) 
	SELECT t.ID, t.ActiveFindDiagnosis, t.Mkb, t.Diagnosis
	FROM @table t

INSERT INTO [AKUZ].[T_ACCOMPANYING_DISEASES] (MedicalRecordID, OutcomeOfInspection, TypeDisease) 
	SELECT t.ID, t.MovementResult, 1
	FROM @table t



ALTER TABLE [AKUZ].[T_MOVEMENT_RESULT] DROP COLUMN [MkbAggravation]
GO
ALTER TABLE [AKUZ].[T_MOVEMENT_RESULT] DROP COLUMN [DiagAggravation]
GO

