I am trying to create a stored procedure in Postgres for generating CSV files containing the average values of some tags/variables between the last 15 minutes. But when I try to implement the 'where' condition for selecting the tag values in the last 15 minutes using Execute 'format()' method, it gives me syntax errors as output. Since the actual code with multiple tags is too complicated, I am having a hard time fixing the syntax of this code. Can you guys please take a look at this? I am doing this in Postgres SQL using PLPGSQL language. Here I am able to add my file name dynamically, but conditions in the select query are generating problems.
CREATE OR REPLACE PROCEDURE public.csv_test0002()
LANGUAGE plpgsql
AS $$
declare sDate varchar;
declare sFileName varchar;
declare DEST varchar;
DECLARE sFromTime varchar(150);
DECLARE sToTime varchar(150);
begin
sDate := to_char(current_timestamp, 'YYYY-MM-DD_HH24_MI_SS');
DEST := concat('Filename_',sDate);
sFromTime := TO_CHAR(current_timestamp - interval '15 minutes', 'YYYY-MM-DD HH24:MI:SS');
sToTime := TO_CHAR(current_timestamp, 'YYYY-MM-DD HH24:MI:SS');
EXECUTE format(
'COPY'
'(select avg(ptvalue) as ptvalue from pro_opc where ptname = ''OPC_SR'' and pttime between ',sFromTime,' and ',sToTime,')'
'to %L CSV HEADER',
'D:\' || DEST || '.csv'
);
end $$;
The problematic part is the sFromTime and sTotime in the select query. Postgres is not recognizing the value inside them. Can you help me correct the syntax of the format() function here so that I can pass the timestamp condition dynamically?!! Output image of current code when the stored procedure is called