select e.BaseEntity, ps.SectionAlias as FieldName, ea.EntitiesAttributesId, ea.SystemType
		into temp table temp_sections
	from FIES.t_plan_section ps 
	    inner 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 = true;
DO 
$$ 
Declare			
		sqltext varchar;
		
BEGIN  
	WHILE ((select count(*) from temp_sections ts where ts.baseentity is not null)>0) LOOP
		--select e.BaseEntity, ea.EntitiesAttributesId, ea.SystemType
			--into baseentityid, primarykey, keytype
		update temp_sections ts
		set baseentity = e.baseentity, entitiesattributesid = ea.entitiesattributesid, systemtype = ea.systemtype
		from VCLib.T_ENTITIES e
			join VCLib.T_ENTITIES_ATTRIBUTES ea on ea.EntityID = e.EntityID and ea.IsPrimaryKey = true
		where ts.baseentity = e.entityid and ts.baseentity is not null;
	END LOOP;

	sqltext := (
					select string_agg('ALTER TABLE FIES.' || ts.TableName || ' ADD ' || s.FieldName || ' ' || (case when s.SystemType = 'guid' then 'uuid' when s.SystemType = 'string' then 'varchar(255)' else s.SystemType end) || ' null;', '')
			--select *		
					from (
								  select 'T_SMO_COEF_MONTH_VALUES'::text as TableName
							--union select 'T_PLAN_ITEM_LIMITS'							
						 ) ts, temp_sections s
			   );
	  
	  EXECUTE sqltext;
END; 
$$ ;

drop table temp_sections;