无法在postgres中运行预准备语句/函数

时间:2017-03-22 13:11:15

标签: postgresql plpgsql

如何获取临时变量中的行并处理/使用其字段? 看到开始部分,我需要获取帐户信息,做一些计算,比如我需要在accountbalance方法中获取Account.field1 - Account.Field2的值,怎么做?      - 这是声明

PREPARE get_account (varchar) AS
SELECT * FROM "Accounts" WHERE "AccountKey" = $1 LIMIT 1;

-- Try to run directly
select EXECUTE(get_account("A200"));


--Created a function and used statement. 
CREATE OR REPLACE FUNCTION accountbalance(VARCHAR) RETURNS REAL AS $$
    DECLARE
    AKey ALIAS FOR $1;  
    balance REAL;
    account RECORD;
BEGIN   
   account := EXECUTE(get_account("A200"));
   --Tried these too
   --account := EXECUTE get_account('A200');    
   --account := EXECUTE get_account("A200");    
   --I need to get account data here, process, How to get data to a declared variable, how user specific column, May be something like Accounts."Total".. 
   --I tried to run direct query here and get data to account, but no success so tried prepared statement. 
   --I will be doing complex calculations here, trying to return a column for test , not sure is it correct? 
RETURN account.Actual;
END;
$$ LANGUAGE plpgsql;

--Used function in sql

Select accountbalance('A200');

在这两种情况下都会收到这样的错误。

错误:列“A200”不存在 第1行:选择EXECUTE(get_account(“A200”));                                    ^

**********错误**********

错误:列“A200”不存在 SQL状态:42703 性格:28

2 个答案:

答案 0 :(得分:1)

选择EXECUTE(get_account(“A200”))时,不执行prepared statement; - 你执行你的功能。以下是如何运行预准备语句的示例:

execute get_account ('a200');

对于你准备的stmt,它将是

EXECUTE

关于在plpgsql块中使用sql EXECUTE(它有自己的{{1}} - 与sql 1非常不同),请阅读https://stackoverflow.com/a/12708117/5315974

答案 1 :(得分:0)

Why you need it? Any embedded SQL in PLpgSQL is implicitly prepared statement. Explicitly prepared statements are not supported in PLpgSQL. Maybe you want to use dynamic SQL - see EXECUTE statement.