IF  EXISTS (SELECT * 
            FROM   dbo.sysobjects 
            WHERE  id = OBJECT_ID(N'[dbo].[sp_UpdateDweToReType]') AND xtype = N'P')
DROP PROCEDURE [dbo].[sp_UpdateDweToReType]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:  Michael Panin
-- Create date: 2023/08/08
-- Description: Смена типа MEDICAL_EXAMINATION_RE на DOCTOR_WARD_EXAMINATION
-- =============================================

CREATE PROCEDURE [dbo].[sp_UpdateDweToReType]
    @newDweId uniqueidentifier, -- Идентификатор нового MEDICAL_EXAMINATION_RE
    @oldDweId uniqueidentifier  -- Идентификатор старого DOCTOR_WARD_EXAMINATION
AS 
BEGIN
	
    UPDATE [AKUZ].T_MEDICAL_RECORD 
    SET    [AKUZ].T_MEDICAL_RECORD.type_ = (SELECT EntityID
                                            FROM   [VCLib].T_ENTITIES
                                            WHERE  EntName = 'MEDICAL_EXAMINATION_RE' AND [Schema] = 'AKUZ')
	WHERE  MedicalRecordID = @oldDweId

    DELETE FROM [AKUZ].T_DOCTOR_WARD_EXAMINATION
    WHERE       MedicalRecordID = @oldDweId

    INSERT INTO [AKUZ].T_MEDICAL_EXAMINATION_RE (MedicalRecordID, MedicalExaminationMain)
    VALUES (@oldDweId, @newDweId)
    
END
GO
