5

我有一个函数,它使用一些 If Else 条件动态生成 SELECT 查询。我将该查询存储在 TEXT 类型变量中

    CREATE OR REPLACE FUNCTION func_updateanswercodes(ans_id_param BIGINT, 
                              que_id_param BIGINT, 
                              overwrite_param INTEGER, 
                              new_ans_code_param CHARACTER VARYING)
    RETURNS INTEGER AS
    $BODY$
...................
................
...................
        dyn_sql = 'SELECT ' || que_col_name || ' INTO old_ans_col_val FROM';
                    IF SUBSTR(que_col_name, 0, 8) = 'pro_ans' THEN
                        dyn_sql = dyn_sql || ' profile_answers JOIN registrations ON (pro_ans_frn_pro_id = reg_frn_pro_id)';
                        ELSIF SUBSTR(que_col_name, 0, 8) = 'reg_ans' THEN
                        dyn_sql = dyn_sql || ' reg_answers ';
                        ELSIF SUBSTR(que_col_name, 0, 8) = 'tvl_ans' THEN
                        dyn_sql = dyn_sql || ' tvl_answers '; --35
                                END IF;
                    dyn_sql = dyn_sql || ' WHERE';
                    IF SUBSTR(que_col_name, 0, 8) = 'pro_ans' THEN
                        dyn_sql = dyn_sql || ' reg_id ';
                        ELSIF SUBSTR(que_col_name, 0, 8) = 'reg_ans' THEN
                        dyn_sql = dyn_sql || ' reg_ans_frn_reg_id ';
                        ELSIF SUBSTR(que_col_name, 0, 8) = 'tvl_ans' THEN
                        dyn_sql = dyn_sql || ' tvl_ans_frn_reg_id ';
                                END IF;
                        dyn_sql = dyn_sql || '= ' || CAST(temp_reg AS VARCHAR) ||';'

    /* Here want to execute that query in variable dync_sql
...........................
.............................
.......................
    END;
    $BODY$
    LANGUAGE plpgsql VOLATILE

但是使用 plpgsql(PL/SQL for postgres) 我不知道如何在变量中执行相同的查询。请帮我解决一下这个 。提前致谢

4

2 回答 2

2

从文档(Postgres 9.1):

EXECUTE command-string [ INTO [STRICT] target ] [ USING expression [, ... ] ];

其中 command-string 是一个表达式,产生一个包含要执行的命令的字符串(文本类型)。可选目标是记录变量、行变量或简单变量和记录/行字段的逗号分隔列表,命令的结果将存储在其中。

换句话说:

Move the INTO old_ans_col_val from the String to the place where you EXECUTE it.

于 2012-12-20T06:35:54.390 回答
1

使用 EXECUTE 获取详细信息,请参阅手册

请注意,您必须从查询字符串中取出 INTO 部分并将其放在末尾。

EXECUTE dyn_sql INTO old_ans_col_val;
于 2012-12-20T06:34:58.133 回答