IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateClassificationGroupsRDS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_UpdateClassificationGroupsRDS]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Vitacore (с)
-- Create date: 2015-07-29
-- Description: Загрузка справочника Классификации групп препаратов
-- =============================================
CREATE PROCEDURE [dbo].[sp_UpdateClassificationGroupsRDS]
    @Xml varchar(max)
    ,@QueueName varchar(100) = 'RDSSync'
    ,@dateTime datetime = null
AS
BEGIN
    SET NOCOUNT ON;

    declare @parsedXml xml

    select @dateTime = ISNULL(@dateTime, GETDATE())
            ,@parsedXml = cast(@Xml as xml)



    -- Получаем данные из XML
    select T.c.value('./Name[1]', 'varchar(255)') as Name
            ,T.c.value('./Code[1]', 'int') as Code
        INTO #classificationgroups
    from @parsedXml.nodes('GROUPS_OF_DRUGS_CLASSIFICATION/body/GROUPS_OF_DRUGS_CLASSIFICATION/GROUP_OF_DRUGS_CLASSIFICATION') T(c)



    -- Загружаем новые лекарственные формы
    INSERT INTO [PHARM].[T_GROUPS_OF_DRUGS_CLASSIFICATION] ([Code], [Name])
    SELECT
               nmf.Code--<Code, int,>
               ,nmf.Name--<Name, varchar(255),>
    from #classificationgroups nmf
    where not exists
        (
            select *
            from [PHARM].T_GROUPS_OF_DRUGS_CLASSIFICATION mf
            where mf.Code = nmf.Code
        )



    -- Обновляем имеющиеся лекарственные формы
    update mf
    set mf.Name = nmf.Name--<Name, int,>
    from [PHARM].T_GROUPS_OF_DRUGS_CLASSIFICATION mf
        join #classificationgroups nmf on nmf.Code = mf.Code
END
