使用变量作为语句的一部分

时间:2018-06-01 13:12:05

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

我想将变量用作语句的一部分,但它表示“tableref”不存在。

.then((myJson) => this.setState({
    data: this.state.data.concat(myJson.issues)
}));

我尝试使用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 ..

1 个答案:

答案 0 :(得分:1)

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

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

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