IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[FIES].[T_PLAN_SECTION_AfterInsert]'))
DROP TRIGGER [FIES].[T_PLAN_SECTION_AfterInsert]
GO

--Добавление записей:
CREATE TRIGGER [FIES].[T_PLAN_SECTION_AfterInsert] ON [FIES].[T_PLAN_SECTION]
AFTER INSERT 
AS
declare @FieldName nvarchar(50), @PrimaryKey uniqueidentifier, @KeyType nvarchar(100), @BaseEntityID int, @sqltext nvarchar(max)

select @BaseEntityID = e.BaseEntity
      ,@FieldName = ps.SectionAlias
      ,@PrimaryKey = ea.EntitiesAttributesId
      ,@KeyType = ea.SystemType
from inserted ps
    join VCLib.T_ENTITIES e on e.EntityID = ps.Entities
    left join VCLib.T_ENTITIES_ATTRIBUTES ea on ea.EntityID = e.EntityID and ea.IsPrimaryKey = 1

WHILE(@BaseEntityID is not null)
	select @BaseEntityID = e.BaseEntity
		  ,@PrimaryKey = ea.EntitiesAttributesId
		  ,@KeyType = ea.SystemType
	from VCLib.T_ENTITIES e
		join VCLib.T_ENTITIES_ATTRIBUTES ea on ea.EntityID = e.EntityID and ea.IsPrimaryKey = 1
where e.EntityID = @BaseEntityID

set @sqltext = 
(
	select N'ALTER TABLE FIES.' + ts.TableName + N' ADD ' + @FieldName + ' ' + (case when @KeyType = 'guid' then N'uniqueidentifier' when @KeyType = 'string' then N'varchar(255)' else @KeyType end) + ' null;'
	from (
	              select N'T_PLAN_ITEM' as TableName
	        union select N'T_PLAN_ITEM_LIMITS'
	        union select N'T_SECTION_DEPEND_SETTINGS'
	        union select N'T_SMO_COEF_MONTH_VALUES'
	        union select N'T_FACT_ITEM'
	        union select N'T_MEETING_RESOLVE'
	        union select N'T_SPLIT_SETTINGS'
	        union select N'T_FACT_ITEM_SUM'
	        union select N'T_EXTERNAL_PLAN_SUM'
	        union select N'T_COEFFICENT_STATINFO'
	        union select N'T_MO_PARAMETER_ITEM'
	        union select N'T_TP_FIN_CLOSE_ITEM'
	        union select N'T_PLAN_FACT_STATISTICS'
	     ) ts
	for xml path('')
)
exec sp_executesql @sqltext
