ALTER TABLE [AKUZ].[T_MEDICAL_RECORD] ADD [MOMain] uniqueidentifier NULL 
GO

UPDATE mr
SET mr.MOMain = b.LpuMain
FROM AKUZ.T_MEDICAL_RECORD mr
JOIN AKUZ.T_RESOURCE r on mr.Post = r.ResourceID
JOIN AKUZ.T_DIVISION d on d.DivisionID = r.Division
JOIN AKUZ.T_BRANCH b on b.LpuID = d.Branch
GO

AlTER TABLE [AKUZ].[T_MEDICAL_RECORD] ALTER COLUMN [MOMain] uniqueidentifier not null
GO

ALTER TABLE [AKUZ].[T_MEDICAL_RECORD] ADD CONSTRAINT [FK_T_LPU_MAIN_T_MEDICAL_RECORD_MOMain]
FOREIGN KEY([MOMain]) REFERENCES [AKUZ].[T_LPU_MAIN] ([LpuID])
GO
