declare @sqltext nvarchar(max)

select e.BaseEntity
      ,ps.SectionAlias as FieldName
      ,ea.EntitiesAttributesId
      ,ea.SystemType
into #temp_sections
from FIES.T_PLAN_SECTION 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((select count(*) from #temp_sections ts where ts.baseentity is not null)>0)
	update ts
		set baseentity = e.baseentity, entitiesattributesid = ea.entitiesattributesid, systemtype = ea.systemtype
		from #temp_sections ts 
		    join VCLib.T_ENTITIES e on ts.baseentity = e.entityid
			join VCLib.T_ENTITIES_ATTRIBUTES ea on ea.EntityID = e.EntityID and ea.IsPrimaryKey = 1
		where ts.baseentity is not null

set @sqltext = 
(
	select N'ALTER TABLE FIES.' + ts.TableName + N' ADD ' + s.FieldName + ' ' + (case when s.SystemType = 'guid' then N'uniqueidentifier' when s.SystemType = 'string' then N'varchar(255)' else s.SystemType end) + ' null;'
	from (
	              select N'T_SMO_COEF_MONTH_VALUES' as TableName
	        --union select N'T_PLAN_ITEM_LIMITS'	        
	     ) ts, #temp_sections s
	for xml path('')
)
drop table #temp_sections
exec sp_executesql @sqltext
