如何在动态 SQL 中为 table 名称使用参数

How to use argument for table name in dynamic SQL

我正在编写一个 Postgres 函数来获取 table 中的新记录数。这里 table name 是一个变量。

create or replace function dmt_mas_updates(
    tb_name text,
    days integer)
    returns integer as
$$
declare
    ct integer;
begin
    execute 'select count(*) from  where etl_create_dtm > now() -  * interval ''1 days'' '
    using tb_name, days into ct;
    return ct;

end;
$$ LANGUAGE 'plpgsql'

当我用 select * from dmt_mas_updates('dmt_mas_equip_store_dim',2); 调用函数时,我在 </code> 处遇到语法错误。 </p> <p>如果我 运行 直接查询 <code>select count(*) from dmt_mas_equip_store_dim where etl_create_dtm >= interval '3 days',它可以正常工作。

为什么会出现此错误?我做错了什么?

the documentation:

Note that parameter symbols can only be used for data values — if you want to use dynamically determined table or column names, you must insert them into the command string textually.

使用format()函数:

create or replace function dmt_mas_updates(
    tb_name text,
    days integer)
    returns integer as
$$
declare
    ct integer;
begin
    execute format(
        'select count(*) from %I where etl_create_dtm > now() -  * interval ''1 days'' ',
        tb_name)
    using days into ct;
    return ct;

end;
$$ LANGUAGE 'plpgsql';