Skip to content

Instantly share code, notes, and snippets.

@docteurklein
Created January 18, 2021 16:00
Show Gist options
  • Save docteurklein/d43d6e63dc7ce10bcee827fc97bf564d to your computer and use it in GitHub Desktop.
Save docteurklein/d43d6e63dc7ce10bcee827fc97bf564d to your computer and use it in GitHub Desktop.
postgres dynamic sql
drop function if exists exec(text, text[]);
create function exec(sql text, params text[] default '{}') returns void
language 'plpgsql' as $$
begin
execute format(sql, variadic params);
end
$$;
-- select exec('select 1');
drop function if exists query(text, text[]);
create function query(sql text, params text[] default '{}') returns setof record
language 'plpgsql' as $$
begin
return query execute format(sql, variadic params);
end
$$;
-- select * from generate_series(1, 10) i, query('select generate_series(%s, %s::int + 10)', array[i::text, i::text]) as g(ii int);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment