2017-03-22 66 views
0

如何獲取臨時變量中的行並處理/使用其字段? 請參閱開始部分,我需要獲取帳戶信息,進行一些計算,例如我需要在帳戶餘額方法中獲得Account.field1 - Account.Field2的值,該怎麼做? - 這是聲明無法在postgres中運行預處理語句/函數

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」不存在 LINE 1:select EXECUTE(get_account(「A200」)); ^

********** **********錯誤

錯誤:列 「A200」 不存在 SQL狀態:42703 字符:28

+1

雙引號用於關係,而不是值 –

+0

當你選擇EXECUTE(get_account(「A200」))時,你不執行預備語句;' - 你執行你的函數 –

+0

我嘗試了所有選項,選擇EXECUTE(get_account ('A200')),然後選擇EXECUTE(get_account(A200)); –

回答

0

爲什麼你需要它? PLpgSQL中的任何嵌入式SQL都是隱式準備語句。 PLpgSQL中不支持顯式準備的語句。也許你想使用動態SQL - 請參閱EXECUTE聲明。

1

當您選擇EXECUTE(get_account(「A200」))時,您不執行prepared statement; - 你執行你的功能。這裏有一個如何來運行準備語句例如:

t=# PREPARE get_account (varchar) AS SELECT * FROM pg_tables where tablename = $1; 
PREPARE 
t=# execute get_account ('pg_statistic'); 
schemaname | tablename | tableowner | tablespace | hasindexes | hasrules | hastriggers 
------------+--------------+------------+------------+------------+----------+------------- 
pg_catalog | pg_statistic | postgres |   | t   | f  | f 
(1 row) 

爲您準備的語句這將是

execute get_account ('a200'); 

關於PLPGSQL塊使用SQL EXECUTE(它有它自己的EXECUTE - 從SQL一個非常不同) ,請閱讀https://stackoverflow.com/a/12708117/5315974

+0

但這不起作用的功能accountbalance(),請參閱我的問題, 帳戶:= EXECUTE get_account('A200'); –

+0

更新了細節 –