作为最后的手段,写这篇文章几乎已经烧掉......
大家好,我希望得到一些我需要创建的第一个功能的帮助。根据我的阅读,我理解您只需要将函数页眉和页脚添加到任何SQL命令集以创建函数。
我有一个视图,我已经创建了哪个工作正常...这是它的代码
CREATE VIEW invoice_v AS
SELECT customer.firstname, lastname, customer_addresses.address, orders.order_id, order_date, order_total, order_details.product_id, quantity, unitprice, product.product_name
FROM customer, customer_addresses, orders, order_details, product
WHERE customer.customer_id = customer_addresses.customer_id
AND customer.customer_id = orders.customer_id
AND orders.order_id = order_details.order_id
AND product.product_id = order_details.product_id;
SELECT firstname, lastname, address, order_id, order_date, product_id, product_name, quantity, unitprice, order_total
FROM invoice_v
WHERE order_id = 02;
它的作用是为Invoice创建一个视图,其中包含order_id 2的所有详细信息。
我需要用函数做类似的事情。我不知道如何做到这一点。
这就是我试图做的......但是失败了,我很抱歉,如果这看起来非常愚蠢,但我是新手......
CREATE FUNCTION invoiceforprint() RETURNS name AS '
SELECT customer.firstname, lastname, customer_addresses.address, orders.order_id, order_date, order_total, order_details.product_id, quantity, unitprice, product.product_name
FROM customer, customer_addresses, orders, order_details, product
WHERE customer.customer_id = customer_addresses.customer_id
AND customer.customer_id = orders.customer_id
AND orders.order_id = order_details.order_id
AND product.product_id = order_details.product_id;
' LANGUAGE SQL;
上面的代码给了我这个错误
ERROR: return type mismatch in function declared to return name
DETAIL: Final statement must return exactly one column.
CONTEXT: SQL function "invoiceforprint"
我甚至不知道我应该为RETURN使用什么参数。 任何有关此事的帮助,将不胜感激。
答案 0 :(得分:0)
抱歉不要靠近postgres DB,所以这是未经测试的。
你所追求的是一个表函数,这里有一个例子http://www.postgresql.org/docs/9.1/static/sql-createfunction.html
CREATE FUNCTION invoiceforprint() RETURNS TABLE(firstname text
, lastname text
, address text
, order_id int
, order_date date
, order_total numeric
, product_id int
, quantity numeric
, unitprice numeric,
, product_name text ) AS
$$
SELECT customer.firstname
, lastname
, customer_addresses.address
, orders.order_id
, order_date
, order_total
, order_details.product_id
, quantity
, unitprice
, product.product_name
FROM customer, customer_addresses, orders, order_details, product
WHERE customer.customer_id = customer_addresses.customer_id
AND customer.customer_id = orders.customer_id
AND orders.order_id = order_details.order_id
AND product.product_id = order_details.product_id;
$$ LANGUAGE SQL;