ALTER FUNCTION public.spCommitHParamsFromVTables(p_pubid varchar(255),p_log bool,p_log_timestamp timestamp,p_log_idUser int)
    RENAME TO spCommitHParamsFromVTables_SaveOldVersion;

CREATE /* OR REPLACE */ FUNCTION public.spCommitHParamsFromVTables(
p_pubid varchar(255),
p_log bool,
p_log_timestamp timestamp = null,
p_log_idUser int = null)
returns void
as $$
declare Rec RECORD;
begin
if not exists (select idParamDef from public.ParamDefs where idParamTable is not null) then
 	return;
end if;
create TEMPORARY table tt_paramTablesInAction(idParamTable int primary key);

execute Format('insert into tt_paramTablesInAction(idParamTable)
select distinct D.idParamTable from ParamDefs D inner join (
select idParamDef from Parameters_STR_%s union 
select idParamDef from Parameters_INT_%s union 
select idParamDef from Parameters_DBL_%s
) P on D.idParamDef=P.idParamDef where D.idParamTable is not null', p_pubid,p_pubid,p_pubid);

FOR Rec IN
select T.idParamTable, T.TableName from public.ParamTables T 
inner join tt_paramTablesInAction ST on T.idParamTable=ST.idParamTable
LOOP
perform public.spCopyHParamsFromUserPubVBuffer(p_pubid, Rec.idParamTable, Rec.TableName, p_log, p_log_timestamp, p_log_idUser);
END LOOP;
drop table tt_paramTablesInAction;

execute Format('delete from Parameters_STR_%s P USING ParamDefs D where P.idParamDef=D.idParamDef AND D.idParamTable is not null',p_pubid);
execute Format('delete from Parameters_INT_%s P USING ParamDefs D where P.idParamDef=D.idParamDef AND D.idParamTable is not null',p_pubid);
execute Format('delete from Parameters_DBL_%s P USING ParamDefs D where P.idParamDef=D.idParamDef AND D.idParamTable is not null',p_pubid);
end; -- End FUNCTION spCommitHParamsFromVTables
$$ language plpgsql;

alter function public.spCommitHParamsFromVTables owner to cadlib_user_role;
