DECLARE @ID UNIQUEIDENTIFIER	
	/*Объявляем курсор*/
	DECLARE @CURSOR CURSOR
	/*Заполняем курсор*/
	SET @CURSOR  = CURSOR SCROLL
	FOR
	SELECT  PlanSectionID  
	  FROM  FIES.T_PLAN_SECTION
	/*Открываем курсор*/
	OPEN @CURSOR
	/*Выбираем первую строку*/
	FETCH NEXT FROM @CURSOR INTO @ID
	/*Выполняем в цикле перебор строк*/
	WHILE @@FETCH_STATUS = 0
	BEGIN
		

DECLARE @fieldname  varchar(50)
declare @xml xml, @PrimaryKeyName varchar(255), @KeyType varchar(100), @BaseEntityID int

SELECT @fieldname = REPLACE(t2.EntName,'_', '')
,@xml = replace(cast(t2.[xml] as varchar(max)),'<?xml version="1.0" encoding="utf-8" standalone="yes"?>','')
,@BaseEntityID = t2.BaseEntity
FROM FIES.T_PLAN_SECTION t1
LEFT JOIN VCLib.T_ENTITIES t2 on t2.EntityID = t1.Entities
WHERE t1.PlanSectionID = @ID

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 VCLib.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 FIES.T_PLAN_FACT_STATISTICS ADD ' + @fieldname + ' ' + (case when @KeyType = 'guid' then 'uniqueidentifier' when @KeyType = 'string' then 'varchar(255)' else @KeyType end) + ' null'
exec sp_executesql @sql

	/*Выбираем следующую строку*/
	FETCH NEXT FROM @CURSOR INTO @ID
	END
	CLOSE @CURSOR
    DEALLOCATE @CURSOR