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

--Добавление записей:
CREATE TRIGGER [dbo].[T_PLAN_SECTION_AfterInsert] ON [dbo].[T_PLAN_SECTION]
AFTER INSERT 
AS
DECLARE @fieldname  varchar(50)
declare @xml xml, @PrimaryKeyName varchar(255), @KeyType varchar(100), @BaseEntityID int

SELECT @fieldname = REPLACE(ISNULL(t2.EntName, t3.EntName),'_', '')+'_'+CAST(t1.SectionLevel as varchar(3))
,@xml = replace(cast(t2.[xml] as varchar(max)),'<?xml version="1.0" encoding="utf-8" standalone="yes"?>','')
,@BaseEntityID = t2.BaseEntity
FROM inserted t1
LEFT JOIN T_ENTITIES t2 on t2.EntityID = t1.Entities
LEFT JOIN T_ADDITIONAL_ENTITIES t3 on t3.EntityID = t1.Entities

if(@xml is null)
begin
	set @KeyType = 'guid'
end
else if (@BaseEntityID is null)
begin
	SELECT
		   @PrimaryKeyName = T.c.value('./@PrimaryKey', 'varchar(max)') 
		 FROM   @xml.nodes('/Entity') T(c)
		 select @PrimaryKeyName

		 SELECT @KeyType=(SELECT aa.[Type] FROM
		 (SELECT
			T.c.value('./@Name', 'varchar(max)') As Name
			,T.c.value('./@Type', 'varchar(max)') AS [Type]
		 FROM   @xml.nodes('/Entity/Fields/Attribute') T(c)) aa
		 WHERE aa.Name= @PrimaryKeyName)
end
else
begin
		WHILE(@KeyType is null)
		begin
				SELECT @xml = replace(cast(t2.[xml] as varchar(max)),'<?xml version="1.0" encoding="utf-8" standalone="yes"?>','')
				,@BaseEntityID = t2.BaseEntity
				FROM T_ENTITIES t2 where t2.EntityID = @BaseEntityID
				SELECT
				   @PrimaryKeyName = T.c.value('./@PrimaryKey', 'varchar(max)') 
				 FROM   @xml.nodes('/Entity') T(c)
				 --select @PrimaryKeyName

				 SELECT @KeyType=(SELECT aa.[Type] FROM
				 (SELECT
					T.c.value('./@Name', 'varchar(max)') As Name
					,T.c.value('./@Type', 'varchar(max)') AS [Type]
				 FROM   @xml.nodes('/Entity/Fields/Attribute') T(c)) aa
				 WHERE aa.Name= @PrimaryKeyName)
		 end
end

declare @sql nvarchar(max)
set @sql = 'ALTER TABLE T_PLAN_ITEM ADD ' + @fieldname + ' ' + (case when @KeyType = 'guid' then 'uniqueidentifier' when @KeyType = 'string' then 'varchar(255)' else @KeyType end) + ' null'
exec sp_executesql @sql
set @sql = 'ALTER TABLE T_PLAN_ITEM_LIMITS ADD ' + @fieldname + ' ' + (case when @KeyType = 'guid' then 'uniqueidentifier' when @KeyType = 'string' then 'varchar(255)' else @KeyType end) + ' null'
exec sp_executesql @sql
set @sql = 'ALTER TABLE T_SECTION_DEPEND_SETTINGS ADD ' + @fieldname + ' ' + (case when @KeyType = 'guid' then 'uniqueidentifier' when @KeyType = 'string' then 'varchar(255)' else @KeyType end) + ' null'
exec sp_executesql @sql
set @sql = 'ALTER TABLE T_PLAN_REQUEST_SMO_ITEM ADD ' + @fieldname + ' ' + (case when @KeyType = 'guid' then 'uniqueidentifier' when @KeyType = 'string' then 'varchar(255)' else @KeyType end) + ' null'
exec sp_executesql @sql