【问题标题】:using variable as part of the statement使用变量作为语句的一部分
【发布时间】:2018-11-11 15:27:58
【问题描述】:

我想在语句中使用一个变量,但它说“tableref”不存在。

CREATE OR REPLACE FUNCTION ff(tipo_acta integer, hasta date)
  RETURNS void AS
$BODY$
DECLARE 
 tableref varchar;
 r record;
BEGIN
 if tipo_acta = 1 then
          tableref = 't1';
 elsif tipo_acta = 2 then tableref = 't2';
 else tableref = 't3';
end if;

for r select id from tableref where somedate >= hasta loop
--
end loop;

我尝试使用EXECUTE 'select id from ' || tableref || ' where....',但也不起作用

我想先用select id into r from t1 where ..获取记录,然后在循环中使用它,但似乎没有办法在这样的循环中使用记录:

FOR r LOOP
....
END LOOP;

【问题讨论】:

    标签: postgresql function plpgsql dynamic-sql postgresql-9.4


    【解决方案1】:

    您需要为此使用动态 sql。您需要在 PLPG/SQL 中使用 execute command 来执行此操作。

    在你的代码中应该是这样的:

    EXECUTE 'SELECT id FROM ' || tableref || ' WHERE somedate >= $1'
    INTO c
    USING hasta;
    

    【讨论】:

    • 谢谢,毕竟我是在正确的道路上FOR r IN EXECUTE ... LOOP
    猜你喜欢
    • 2017-01-07
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多