--
-- Name: plan_section_forupdate(); Type: FUNCTION; Schema: public; Owner: postgres
--
CREATE or replace FUNCTION plan_section_forupdate() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
Declare	
		fieldnamefrom varchar;
		fieldnameto varchar;
		sqltext varchar;
BEGIN

	select Old.SectionAlias, New.SectionAlias
		into fieldnamefrom, fieldnameto
	from VCLib.T_ENTITIES ei
		left join VCLib.T_ENTITIES_ATTRIBUTES eai on eai.EntityID = ei.EntityID and eai.IsPrimaryKey = 1
	where ei.EntityID = New.Entities;

	sqltext := (
					select string_agg('ALTER TABLE FIES.' || ts.TableName || ' RENAME COLUMN ' || fieldnamefrom || ' TO ' || fieldnameto || ';', '')
					from (
								  select 'T_PLAN_ITEM' as TableName
							union select 'T_PLAN_ITEM_LIMITS'
							union select 'T_SECTION_DEPEND_SETTINGS'
							union select 'T_SMO_COEF_MONTH_VALUES'
							union select 'T_FACT_ITEM'
							union select 'T_MEETING_RESOLVE'
							union select 'T_SPLIT_SETTINGS'
							union select 'T_FACT_ITEM_SUM'
							union select 'T_EXTERNAL_PLAN_SUM'
							union select 'T_COEFFICENT_STATINFO'
							union select 'T_MO_PARAMETER_ITEM'
							union select 'T_TP_FIN_CLOSE_ITEM'
							union select 'T_PLAN_FACT_STATISTICS'
						 ) ts
			   );
	EXECUTE sqltext;

	Return New;

END;
$$;



--
-- Name: plan_section_forupdate; Type: TRIGGER; Schema: public; Owner: sa
--
DO 
$$ 
BEGIN 
IF EXISTS(SELECT * 
                     FROM information_schema.triggers 
                     WHERE event_object_table = lower('T_PLAN_SECTION') 
                     AND trigger_name = lower('plan_section_forupdate')
                     ) 
                    THEN 
                    DROP TRIGGER plan_section_forupdate ON FIES.T_PLAN_SECTION;
    END IF ; 

END; 
$$ ;

CREATE TRIGGER plan_section_forupdate AFTER UPDATE OF SectionAlias ON FIES.T_PLAN_SECTION FOR EACH ROW EXECUTE PROCEDURE plan_section_forupdate();
