IF NOT EXISTS (SELECT * FROM sys.tables t 
               JOIN sys.schemas s ON t.schema_id = s.schema_id 
               WHERE s.name = 'AKUZ' AND t.name = 'T_ADD_HOSPITAL_SERVICE')
BEGIN

    CREATE TABLE [AKUZ].[T_ADD_HOSPITAL_SERVICE]
    (
        [MedicalRecordID] uniqueidentifier NOT NULL,
        [II] bit NOT NULL
    )
    ON [PRIMARY]
    
    ALTER TABLE [AKUZ].[T_ADD_HOSPITAL_SERVICE] ADD CONSTRAINT [PK_T_ADD_HOSPITAL_SERVICE]
    PRIMARY KEY CLUSTERED ([MedicalRecordID]) ON [PRIMARY]
    
    ALTER TABLE [AKUZ].[T_ADD_HOSPITAL_SERVICE] ADD CONSTRAINT [FK_T_HOSPITAL_SERVICE_T_ADD_HOSPITAL_SERVICE_MedicalRecordID]
    FOREIGN KEY([MedicalRecordID]) REFERENCES [AKUZ].[T_HOSPITAL_SERVICE] ([MedicalRecordID])

    insert into AKUZ.T_ADD_HOSPITAL_SERVICE (MedicalRecordID, II)
    select MedicalRecordID, 0
    from AKUZ.T_MEDICAL_RECORD mr
    where exists (select 1 from VCLib.T_ENTITIES e
	    where e.EntName = 'ADD_HOSPITAL_SERVICE' and e.[Schema] = 'AKUZ' and e.EntityID = mr.type_)

END
GO