if exists (SELECT *  FROM sys.indexes  WHERE name='IX_T_CARD_EPICRISIS_MovementsDivisionCard' 
    AND object_id = OBJECT_ID('AKUZ.T_CARD_EPICRISIS'))
	begin
	drop index IX_T_CARD_EPICRISIS_MovementsDivisionCard on AKUZ.T_CARD_EPICRISIS
	end
GO

ALTER TABLE AKUZ.T_CARD_EPICRISIS ADD MedicalEpisode uniqueidentifier NULL
GO

update card
set card.MedicalEpisode = card.MovementsDivisionCard
from AKUZ.T_CARD_EPICRISIS card 
where MovementsDivisionCard is not null

DELETE FROM AKUZ.T_CARD_EPICRISIS where MovementsDivisionCard IS NULL

ALTER TABLE AKUZ.T_CARD_EPICRISIS ALTER COLUMN MedicalEpisode uniqueidentifier NOT NULL 
GO

ALTER TABLE AKUZ.T_CARD_EPICRISIS DROP CONSTRAINT FK_T_MOVEMENTS_DIVISION_CARD_T_CARD_EPICRISIS_MovementsDivisionCard
GO

ALTER TABLE AKUZ.T_CARD_EPICRISIS DROP COLUMN MovementsDivisionCard
GO

ALTER TABLE AKUZ.T_CARD_EPICRISIS ADD CONSTRAINT FK_T_MEDICAL_EPISODE_T_CARD_EPICRISIS_MedicalEpisode
FOREIGN KEY(MedicalEpisode) REFERENCES AKUZ.T_MEDICAL_EPISODE (MedicalEpisodeID)
GO
