2014-10-22 52 views
0

我有一個任務,需要我從pgAdminIII中的表中提取多行,將行數據操縱成幾個新的行類型(或者只是以某種方式生成數據)。如何創建可以使用python腳本調用的postgresql函數?

因爲實際的操作似乎很難做到使用基本的sql命令,所以我決定嘗試創建一個postgresql存儲過程(或函數)。到目前爲止,我所得到的都是語法錯誤。

我的PostgreSQL的功能:

CREATE FUNCTION getAllPayments(double precision, double precision, timestamp) RETURNS text AS $$ 
 
DECLARE 
 
credLim ALIAS FOR $1; 
 
paid ALIAS FOR $2; 
 
pdate ALIAS FOR $3; 
 
totalpayments double precision; 
 
numberofpayments integer; 
 
availablecredit double precision; 
 
BEGIN 
 
IF payments.customernumber = orders.customernumber THEN 
 
\t numberofpayments := COUNT(pdate); 
 
\t totalpayments := SUM(paid); 
 
\t availablecredit := credLim + totalpayments - numberofpayments; 
 
SELECT customers.customername, customers.customernumber, credLim, availablecredit, totalpayments, numberofpayments from customers, payments; 
 
ELSE 
 
Return "failed attempt"; 
 
END IF; 
 

 
END;

,這就是調用它的python腳本:

get_data = "getAllPayments(customers.creditlimit, payments.amount, payments.paymentdate)" 
 
seperator = "---------------------------------------------------------------------------------" 
 

 
crsr2 = conn.cursor() 
 
crsr2.execute(get_data) 
 

 
print('Customer Number Customer Name Payments Made Value of Orders Credit Limit Available Credit') 
 
print(seperator) 
 
for x in crsr2: 
 
    neu = str(x) 
 
    w = neu.replace(', ', ',  ') 
 
    print(w) 
 
print(seperator)

+0

這並沒有回答這個問題,但我忍不住發表評論:爲什麼不直接從PostgreSQL中檢索所有數據,然後在Python中操作數據?當然,Python比PostgreSQL過程更容易使用? – wookie919 2014-10-22 01:18:36

回答

1

我看

ERROR: unterminated dollar-quoted string at or near "$$

終止該字符串,並告訴dbms您正在使用哪種語言。

CREATE FUNCTION getAllPayments(double precision, double precision, timestamp) 
RETURNS text AS $$ 
DECLARE 
    credLim ALIAS FOR $1; 
    paid ALIAS FOR $2; 
    pdate ALIAS FOR $3; 
    totalpayments double precision; 
    numberofpayments integer; 
    availablecredit double precision; 
BEGIN 
    IF payments.customernumber = orders.customernumber THEN 
     numberofpayments := COUNT(pdate); 
     totalpayments := SUM(paid); 
     availablecredit := credLim + totalpayments - numberofpayments; 

     SELECT customers.customername, customers.customernumber, credLim, availablecredit, totalpayments, numberofpayments from customers, payments; 

    ELSE 
     Return "failed attempt"; 
    END IF; 
END; 
$$     -- Terminate the string. 
language plpgsql; -- Identify the language. 

這應該讓它編譯。我沒有嘗試,看它是否是有道理的,但我注意到,該行

 availablecredit := credLim + totalpayments - numberofpayments; 

看起來有點可疑,並且不使用ANSI連接通常是一個壞主意。

相關問題