【问题标题】:How to pass schema name dynamically in a function?如何在函数中动态传递架构名称?
【发布时间】:2022-11-22 21:29:56
【问题描述】:

我有一个名为list_customers 的函数,将i_entity_id, i_finyear 作为输入参数。模式名称是从i_finyear 构建的,我需要根据给定的模式执行查询。

我尝试了以下代码:

CREATE OR REPLACE FUNCTION list_customers(i_entity_id integer,
i_finyear integer) 
RETURNS TABLE(entity_id integer, client_id
integer, financial_yr integer) LANGUAGE 'plpgsql' AS 
$BODY$
declare finyear integer := i_finyear; 
    schema_1 text := 'tds'||''||i_finyear;
begin 
    set search_path to schema_1;
return query select
d.entity_id, d.client_id, d.financial_yr
from schema_1.deductor d where d.entity_id = 1331;
end; 
$BODY$;

然后:

select tds2020.list_customers(1331,2022);
   

imagelink

【问题讨论】:

    标签: postgresql plpgsql dynamic-sql postgresql-11


    【解决方案1】:

    您需要使用 EXECUTE 的动态 SQL:

    CREATE OR REPLACE FUNCTION list_customers(i_entity_id int, i_finyear int)
      RETURNS TABLE (entity_id int, client_id int, financial_yr int)
      LANGUAGE plpgsql AS
    $func$
    BEGIN
       RETURN QUERY EXECUTE 
         'SELECT d.entity_id, d.client_id, d.financial_yr
          FROM   tds' || i_finyear || '.deductor d
          WHERE  d.entity_id = $1'
       USING i_entity_id;
    END
    $func$;
    

    由于输入参数 i_finyear 的类型为 integer,因此不存在 SQL 注入的危险,您可以使用普通连接来连接您的模式名称,例如“tbl2016”.否则,您将使用 format() 来防御它。看:

    能够也连接(正确引用)价值观, 但使用 USING 关键字传递值更安全、更高效。看:

    无需更改search_path此外.那只会增加一个昂贵的上下文切换。

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 1970-01-01
      • 2019-12-04
      • 2021-05-16
      • 2015-09-10
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多