2014-10-22 69 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连接通常是一个坏主意。

相关问题