IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[AKUZ].[T_MKF_DIAGNOSIS]') 
         AND name = 'EventRehabilitationCard'
)

BEGIN
	ALTER TABLE [AKUZ].[T_MKF_DIAGNOSIS] ADD [EventRehabilitationCard] uniqueidentifier NULL
END	
GO

UPDATE MKF
SET MKF.EventRehabilitationCard = COALESCE(FPR.EventRehabilitationCard, SPR.EventRehabilitationCard, THR.EventRehabilitationCard) 
FROM [AKUZ].[T_MKF_DIAGNOSIS] MKF
	LEFT JOIN [AKUZ].[T_FIRST_PHASE_REHABILITATION] FPR ON FPR.PhaseRehabilitationID = MKF.PhaseRehabilitation
	LEFT JOIN [AKUZ].[T_SECOND_PHASE_REHABILITATION] SPR ON SPR.PhaseRehabilitationID = MKF.PhaseRehabilitation
	LEFT JOIN [AKUZ].[T_THIRD_PHASE_REHABILITATION] THR ON THR.PhaseRehabilitationID = MKF.PhaseRehabilitation

ALTER TABLE [AKUZ].[T_MKF_DIAGNOSIS] ALTER COLUMN [EventRehabilitationCard] uniqueidentifier NOT NULL

ALTER TABLE [AKUZ].[T_MKF_DIAGNOSIS] ADD CONSTRAINT [FK_T_EVENT_REHABILITATION_CARD_T_MKF_DIAGNOSIS_EventRehabilitationCard]
FOREIGN KEY([EventRehabilitationCard]) REFERENCES [AKUZ].[T_EVENT_REHABILITATION_CARD] ([EventRehabilitationCardID])
