Я пытаюсь создать скользящее окно в PostgreSQL, включая некоторое время l oop, но я запускаю это:
CREATE OR REPLACE FUNCTION for_loop_through_query(sql text)
RETURNS TABLE (name text, rowcount integer) AS $$
declare
yyyymmddtrbeg varchar :='';
yyyymmddtrend varchar :='';
sql1 varchar := '';
sql3 varchar := '';
sql2 varchar :=
'SELECT m.id
FROM merchants AS m
WHERE t.server_time_created_at >= ''yyyymmddtrbeg'' and t.server_time_created_at <''<yyyymmddtrend>''))';
year int := 2019;
counter_mon int := 7;
counter_ttl int := 2;
begin
while counter_ttl > 0 loop
while counter_mon <=12 and counter_ttl > 0 loop
yyyymmddtrbeg := (select cast(year as varchar(4)) + '-' + right('0' + cast (counter_mon as varchar(2)),2) + '-01');
yyyymmddtrend := (select case when counter_mon in (11,12) then cast(year+1 as varchar(4)) else cast(year as varchar(4)) end
+ '-' + right('0' + case when counter_mon = 12 then '02'
when counter_mon = 11 then '01' else
right('0' + cast (counter_mon+2 as varchar(2)),2) end + '-01'));
sql3 := sql2;
sql3 := replace(sql3,'<yyyymmddtrbeg>', yyyymmddtrbeg );
sql3 := replace(sql3,'<yyyymmddtrend>', yyyymmddtrend );
sql1 := sql1 + sql3;
counter_mon := counter_mon + 1;
counter_ttl := counter_ttl - 1;
if counter_ttl <> 0
then sql1 := sql1 + ' union all ';
end loop;
counter_mon := 1; year := year + 1;
end loop; exec (sql1);
end
$$ LANGUAGE plpgsql;
выдает ошибку о первом конце l oop:
ERROR: syntax error at or near "loop"
end loop;
^
SQL state: 42601
Может кто-нибудь сказать мне, как это исправить, пожалуйста?