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
	
	UPDATE MKF
	SET MKF.EventRehabilitationCard = FPR.EventRehabilitationCard
	FROM [AKUZ].[T_MKF_DIAGNOSIS] MKF
	INNER JOIN [AKUZ].[T_FIRST_PHASE_REHABILITATION] FPR ON MKF.PhaseRehabilitation = FPR.PhaseRehabilitationID

	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])
END

