ALTER VIEW [dbo].[V_ENTITY_ATTRIBUTES]
AS
    select
    NEWID() AS [EntityAttributesID] ,
    t2.EntityID AS [EntityID],
    t2.EntityID*10000+900 AS [Index],
    1 AS [AttributeType],
    'QualityQuestionGroup' AS [Name],
    'Группа вопросов-критериев качества' AS  [Description],
    'IES.QUALITY_QUESTION_GROUP' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    CAST(NULL  AS int) AS [Precision],
    CAST(NULL  AS int) AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(0 as bit) AS   [IsRequired],
    4 AS [MappingType],
    CAST(NULL  AS varchar(255)) AS   [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CASE WHEN (SELECT COUNT(*) FROM [IES].T_QUALITY_QUESTION_GROUP)= 0 THEN '<lx:ConstOperand isNull="1" xmlns:lx="lexem" />'
         ELSE '<lx:QueryValue entity="IES.QUALITY_QUESTION_GROUP" top="1"  xmlns:lx="lexem">
        <condition>
            <lx:Criterion type="=">
                <lx:Path OwnerQueryLevel="0">
                    <lx:StepString name="QualityQuestionGroupID" />
                </lx:Path>
                <lx:Case>' +
                 (
                    CAST((SELECT  CAST('<When xmlns:lx="lexem">
                        '+ REPLACE([dbo].[RegExReplace](cast(t1.ConditionLexem as varchar(max)), '<lx:BaseObjectOperand Entity="[\w\.]+" PrimaryKey="(?<guid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})"\s*\/>', '<lx:ConstOperand type="Guid">${guid}</lx:ConstOperand>'), '<lx:Path OwnerQueryLevel="0">', '<lx:Path OwnerQueryLevel="1">')
                         +'
                    </When>
                    <Then xmlns:lx="lexem">
                        <lx:ConstOperand type="Guid">' + CAST(t1.QualityQuestionGroupID as varchar(36)) + '</lx:ConstOperand>
                    </Then>' AS xml)
                    FROM [IES].T_QUALITY_QUESTION_GROUP t1
                    --ORDER BY t1.[Priority]
                    FOR XML PATH(''), TYPE    ) AS VARCHAR(MAX))    
                    
                 )
                 + '            <Else>
                        <lx:ConstOperand isNull="1" />
                    </Else>
                </lx:Case>
            </lx:Criterion>
        </condition>
        <value>
            <lx:Path OwnerQueryLevel="0">
                <lx:StepString name="QualityQuestionGroupID" />
            </lx:Path>
        </value>
    </lx:QueryValue>'
         END AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(NULL  AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST(NULL  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    -1 AS [AttributeId]
    FROM [VCLib].T_ENTITIES t2 
    where EntName= 'MEDICAL_REQUEST_ITEM'
   
    UNION ALL

    -- Поля класификаторов и параметров плана и факта
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    t2.EntityID AS [EntityID],
    t2.EntityID*10000+900+t1.SectionLevel AS [Index],
    1 AS [AttributeType],
    t1.SectionAlias AS [Name],
    t1.Name AS  [Description],
    (case when t3.EntName is not null then t3.[Schema]+'.'+t3.EntName else null end) AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    CAST(NULL  AS int) AS [Precision],
    CAST(NULL  AS int) AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(0 as bit) AS   [IsRequired],
    1 AS [MappingType],
    t1.SectionAlias as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(NULL  AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST(NULL  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (900+(select max(SectionLevel)+1 from [IES].T_PLAN_SECTION)-t1.SectionLevel) * -1 AS [AttributeId]
    FROM IES.T_PLAN_SECTION t1
    JOIN VCLib.T_ENTITIES t2 on t2.EntName in ('SCHET_ITEM_FAKT', 'ITEM_PLAN_MODIFICATION')
    LEFT JOIN VCLib.T_ENTITIES t3 on t3.EntityID = t1.Entities
    WHERE t1.DateBegin <= GETDATE() and (t1.DateEnd is null or t1.DateEnd >= GETDATE())

    UNION ALL

    -- Поля для классифицирующей сущщности связки между планом и фактом
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    t2.EntityID AS [EntityID],
    null AS [Index],
    1 AS [AttributeType],
    t1.SectionAlias AS [Name],
    t1.Name AS  [Description],
    (case when t3.EntName is not null then t3.[Schema]+'.'+t3.EntName else null end) AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    CAST(NULL  AS int) AS [Precision],
    CAST(NULL  AS int) AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    t1.SectionAlias as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(NULL  AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST(NULL  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (900+(select max(SectionLevel)+1 from [IES].T_PLAN_SECTION)-t1.SectionLevel) * -1 AS [AttributeId]
    FROM IES.T_PLAN_SECTION t1
    JOIN VCLib.T_ENTITIES t2 on t2.EntName= 'PLAN_CLASSIFICATION'
    LEFT JOIN VCLib.T_ENTITIES t3 on t3.EntityID = t1.Entities
    where t1.ClassificationType = 0 and t1.DateBegin <= GETDATE() and (t1.DateEnd is null or t1.DateEnd >= GETDATE())

    UNION ALL

    -- Поля для сгруппированных значений параметров в записях плана и факта
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    e.EntityID AS [EntityID],
    null AS [Index],
    0 AS [AttributeType],
    cs.FieldName AS [Name],
    ISNULL(cs.FieldDescription, cs.FieldName) AS [Description],
    'float' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    31 AS [Precision],
    10 AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    cs.FieldName as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(e.MappingTable AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST('<?xml version="1.0" encoding="utf-16"?><Customs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Custom Name="FieldName" Value="' + cs.FieldName + '" /><Custom Name="PlanFactFieldType" Value="1" /></Customs>'  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (900-cs.[Priority]) * -1 AS [AttributeId]
    FROM IES.T_CLASSIFICATION_SETTING cs,
    (
        select e.EntityID, pkEa.MappingTable
        from VCLib.T_ENTITIES e
        left join VCLib.T_ENTITIES_ATTRIBUTES pkEa on pkEa.EntityID = e.EntityID and pkEa.IsPrimaryKey = 1
        where e.EntName in ('ITEM_FACT', 'ITEM_PLAN')
    ) e
    where cs.FieldName is not null

    UNION ALL

    -- Поля для сгруппированных значений параметров по разделу в записях плана и факта
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    e.EntityID AS [EntityID],
    null AS [Index],
    0 AS [AttributeType],
    sections.SectionAlias + cs.FieldName AS [Name],
    ISNULL(cs.FieldDescription + ' (по разделу '+ sections.SectionAlias + ')', sections.SectionAlias + cs.FieldName) AS [Description],
    'float' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    31 AS [Precision],
    10 AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    sections.SectionAlias + cs.FieldName as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(e.MappingTable AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST('<?xml version="1.0" encoding="utf-16"?><Customs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Custom Name="FieldName" Value="' + cs.FieldName + '" /><Custom Name="PlanFactFieldType" Value="4" />'
        + case 
            when sections.PlanSectionID = sections.LastSection then '<Custom Name="NotDisplayedInFilter" Value="True" />'
            else ''
        end
        + case 
            when sections.PlanSectionID = sections.LastSection then '<Custom Name="NotDisplayedColumns" Value="True" />'
            else ''
        end
        + '</Customs>'  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (1000-cs.[Priority]) * -1 AS [AttributeId]
    FROM IES.T_CLASSIFICATION_SETTING cs,
    (
        select e.EntityID, pkEa.MappingTable
        from VCLib.T_ENTITIES e
        left join VCLib.T_ENTITIES_ATTRIBUTES pkEa on pkEa.EntityID = e.EntityID and pkEa.IsPrimaryKey = 1
        where e.EntName in ('ITEM_FACT', 'ITEM_PLAN')
    ) e,
    (
        select *, (
                select top 1 PlanSectionID
                from IES.T_PLAN_SECTION
                where DateBegin <= GETDATE() and (DateEnd is null or DateEnd >= GETDATE()) and ClassificationType = 0
                order by SectionLevel desc
            ) as LastSection
        from IES.T_PLAN_SECTION ps
        where ps.DateBegin <= GETDATE() and (ps.DateEnd is null or ps.DateEnd >= GETDATE()) and ps.ClassificationType = 0
    ) sections
    where cs.FieldName is not null and cs.CalculateSectionsSum = 1

    UNION ALL

    -- Поля остатка плана
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    e.EntityID AS [EntityID],
    null AS [Index],
    0 AS [AttributeType],
    cs.FieldName + 'Rest' AS [Name],
    ISNULL(cs.FieldDescription, cs.FieldName) + ' (Остаток)' AS [Description],
    'float' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    31 AS [Precision],
    10 AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    cs.FieldName + 'Rest' as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(e.MappingTable AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST('<?xml version="1.0" encoding="utf-16"?><Customs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Custom Name="FieldName" Value="' + cs.FieldName + '" /><Custom Name="PlanFactFieldType" Value="2" /></Customs>'  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (900-cs.[Priority]) * -1 AS [AttributeId]
    FROM IES.T_CLASSIFICATION_SETTING cs,
    (
        select e.EntityID, pkEa.MappingTable
        from VCLib.T_ENTITIES e
        left join VCLib.T_ENTITIES_ATTRIBUTES pkEa on pkEa.EntityID = e.EntityID and pkEa.IsPrimaryKey = 1
        where e.EntName in ('ITEM_PLAN')
    ) e
    where cs.FieldName is not null

    UNION ALL

    -- Поля остатка плана по разделу
    SELECT 
    NEWID() AS [EntityAttributesID] ,
    e.EntityID AS [EntityID],
    null AS [Index],
    0 AS [AttributeType],
    sections.SectionAlias + cs.FieldName + 'Rest' AS [Name],
    ISNULL(cs.FieldDescription, cs.FieldName) + ' (Остаток по разделу ' + sections.SectionAlias + ')' AS [Description],
    'float' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    31 AS [Precision],
    10 AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    sections.SectionAlias + cs.FieldName + 'Rest' as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(e.MappingTable AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST('<?xml version="1.0" encoding="utf-16"?><Customs xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Custom Name="FieldName" Value="' + cs.FieldName + '" /><Custom Name="PlanFactFieldType" Value="6" />'
        + case 
            when sections.PlanSectionID = sections.LastSection then '<Custom Name="NotDisplayedInFilter" Value="True" />'
            else ''
        end
        + case 
            when sections.PlanSectionID = sections.LastSection then '<Custom Name="NotDisplayedColumns" Value="True" />'
            else ''
        end
        + '</Customs>'  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    (900-cs.[Priority]) * -1 AS [AttributeId]
    FROM IES.T_CLASSIFICATION_SETTING cs,
    (
        select e.EntityID, pkEa.MappingTable
        from VCLib.T_ENTITIES e
        left join VCLib.T_ENTITIES_ATTRIBUTES pkEa on pkEa.EntityID = e.EntityID and pkEa.IsPrimaryKey = 1
        where e.EntName in ('ITEM_PLAN')
    ) e,
    (
        select *, (
                select top 1 PlanSectionID
                from IES.T_PLAN_SECTION
                where DateBegin <= GETDATE() and (DateEnd is null or DateEnd >= GETDATE()) and ClassificationType = 0
                order by SectionLevel desc
            ) as LastSection
        from IES.T_PLAN_SECTION ps
        where ps.DateBegin <= GETDATE() and (ps.DateEnd is null or ps.DateEnd >= GETDATE()) and ps.ClassificationType = 0
    ) sections
    where cs.FieldName is not null and cs.CalculateSectionsSum = 1

    UNION ALL

    SELECT 
    NEWID() AS [EntityAttributesID] ,
    540 AS [EntityID],
    5400024 AS [Index],
    4 AS [AttributeType],
    'SchetType' AS [Name],
    'Тип счёта' AS  [Description],
    '' AS   [SystemType],
    CAST(NULL  AS int) AS [MaxLength],
    CAST(NULL  AS int) AS [Precision],
    CAST(NULL  AS int) AS [Scale],
    CAST(NULL  AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(0 as bit) AS   [IsRequired],
    4 AS [MappingType],
    CAST(NULL  AS varchar(255)) AS   [MappingName],
    CAST(1 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    '<?xml version="1.0" encoding="utf-16"?>
<ChoiceItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ChoiceItem Name="Счет ОМС" Index="693"></ChoiceItem>
<ChoiceItem Name="Счет МТР от МО" Index="554"></ChoiceItem>
<ChoiceItem Name="Исходящий счет по МТР" Index="539"></ChoiceItem>
<ChoiceItem Name="Входящий счет по МТР" Index="538"></ChoiceItem> 
<ChoiceItem Name="Исправленный счет МТР" Index="555"></ChoiceItem>
<ChoiceItem Name="Временный счет(для расчета)" Index="562"></ChoiceItem>
<ChoiceItem Name="Еженедельные диспансерные счета-реестры" Index="6666"></ChoiceItem>
<ChoiceItem Name="Счёт-реестр ФМО" Index="65432"></ChoiceItem>
    <ChoiceItem Name="Добавленный счет" Index="'+
    (select CAST((select EntityID from VCLib.T_ENTITIES where EntName = 'ADDED_SCHET')  AS varchar(15)))
    +'"></ChoiceItem><ChoiceItem Name="Счёт-реестр тестирования COVID-19" Index="'+ 
    (select CAST((select EntityID from VCLib.T_ENTITIES where EntName = 'COVID_SCHET')  AS varchar(15)))
+'"></ChoiceItem></ChoiceItems>' AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    '<lx:Path OwnerQueryLevel="0" xmlns:lx="lexem">
    <lx:StepString name="ObjectProperties" />
    <lx:StepString name="ObjectTypeID" />
</lx:Path>' AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(NULL  AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    CAST(NULL  AS VARCHAR(8000)) as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    -1 AS [AttributeId]

    UNION ALL

    SELECT 
    NEWID() AS [EntityAttributesID] ,
    e.EntityID AS [EntityID],
    null AS [Index],
    0 AS [AttributeType],
    'IsDelete' AS [Name],
    'Удалён' AS [Description],
    'bool' AS [SystemType],
    CAST(NULL AS int) AS [MaxLength],
    CAST(NULL AS int) AS [Precision],
    CAST(NULL AS int) AS [Scale],
    CAST(NULL AS varchar(255)) AS   [DefaultFormat],
    CAST(0 as bit) AS  [IsCalculated],
    CAST(0 as bit) AS   [IsFlag] ,
    CAST(1 as bit) AS   [IsRequired],
    1 AS [MappingType],
    'IsDelete' as [MappingName],
    CAST(0 as bit) AS   [Save],
    CAST(NULL  AS varchar(255)) AS   [LinkAttributeName],
    CAST(NULL  AS varchar(1024)) AS   [ChoiceAttributeData],
    CAST(1 as bit) AS   [IsStored],
    CAST(NULL  AS varchar(max)) AS   [AttrLexem],
    CAST(NULL  AS varchar(max)) AS   [PathsAttributes],
    CAST(0  AS bit) AS   [IsCashed],
    CAST(null AS varchar(255)) as [MappingTable],
    CAST(NULL  AS VARCHAR(255)) AS [MappingRefTable],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableSearchMode],
    CAST(NULL  AS VARCHAR(255)) AS [RefTableHashFunc],
    CAST(NULL  AS VARCHAR(8000)) as [ParametersData],
    '<Customs><Custom Name="IsDeleteAttribute" Value="True" /></Customs>' as [CustomsData],
    CAST(NULL  AS VARCHAR(8000)) as [RequiredAttributes],
    CAST(NULL  AS VARCHAR(8000)) as [SortingAttribute],
    CAST(NULL  AS VARCHAR(8000)) as [EnumType],
    CAST(0  AS bit) AS [IsIdentity],
    CAST(0  AS bit) AS [IsCustom],
    CAST(1  AS bit) AS [RemoveAction],
    CAST(0  AS bit) AS [IsPrimaryKey],
    -1 AS [AttributeId]
    FROM IES.T_POSTPONED_DELETE_ENTITY pde
        join VCLib.T_ENTITIES e on e.[Schema] + '.' + e.EntName = pde.Name
        join VCLib.T_ENTITIES_ATTRIBUTES pkEa on pkEa.EntityID in (select eh.BaseEntity from V_ENTITY_HIERARCHY eh where eh.EntityID = e.EntityID) and pkEa.IsPrimaryKey = 1
    where pde.IsActive = 1
