Dynamic Commands in PL/pgSQL
The execute
keyword allows you to run a dynamic command - where perhaps a table or column name is not known ahead of time.
1create or replace function get_row_count(table_name text)2 returns integer3 as $$4declare5 c int;6begin7 execute format('select count(*) from %I', table_name) into c;8
9 return c;10end;11$$ language plpgsql;12
13create table s (id serial primary key);14insert into s default values;15
16create table t (id serial primary key);17insert into t default values;18insert into t default values;19
20select get_row_count('s'); -- 121select get_row_count('t'); -- 2
Some notes from the docs:
- There is no plan caching for dynamic commands - commands executed via
execute
. - Be careful not to do something like
key = null
, wherenull
is passed in dynamically. (Useis distinct from
). - See the
using
clause for passing parameters to the dynamic command.
You can read more about this here.
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.