使用变量作为语句的一部分
using variable as part of the statement
我想使用变量作为语句的一部分,但它说 "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;
为此您需要使用动态 sql。您需要使用 execute
command 在 PLPG/SQL 中执行此操作。
在你的代码中应该是这样的:
EXECUTE 'SELECT id FROM ' || tableref || ' WHERE somedate >= '
INTO c
USING hasta;
我想使用变量作为语句的一部分,但它说 "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;
为此您需要使用动态 sql。您需要使用 execute
command 在 PLPG/SQL 中执行此操作。
在你的代码中应该是这样的:
EXECUTE 'SELECT id FROM ' || tableref || ' WHERE somedate >= '
INTO c
USING hasta;