PL/pgSQL RETURNS TABLE 例子

简介:
+关注继续查看

实验如下:

RETURNS TABLE 中的变量名和SQL文中的变量名同名时,执行时会出错:

复制代码
pgsql=# create table sales(itemno integer,quantity integer,price numeric);
CREATE TABLE
pgsql=# insert into sales values (100,15,11.2),(101,22,12.3);
INSERT 0 2
pgsql=# CREATE FUNCTION extended_sales(p_itemno int)
pgsql-# RETURNS TABLE(quantity int, total numeric) AS $$
pgsql$# BEGIN
pgsql$#     RETURN QUERY SELECT quantity, quantity * price FROM sales
pgsql$#                  WHERE itemno = p_itemno;
pgsql$# END;
pgsql$# $$ LANGUAGE plpgsql;
CREATE FUNCTION
pgsql=# 
复制代码
复制代码
pgsql=# select extended_sales(101);
ERROR:  column reference "quantity" is ambiguous
LINE 1: SELECT quantity, quantity * price FROM sales
               ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  SELECT quantity, quantity * price FROM sales
                 WHERE itemno = p_itemno
CONTEXT:  PL/pgSQL function "extended_sales" line 2 at RETURN QUERY
pgsql=# 
复制代码

此时,可以如此操作:

复制代码
pgsql$#     RETURN QUERY SELECT sales.quantity, sales.quantity * sales.price FROM sales
pgsql$#                  WHERE itemno = p_itemno;
pgsql$# END;
pgsql$# $$ LANGUAGE plpgsql;
CREATE FUNCTION
pgsql=# 
pgsql=# select extended_sales(101);
 extended_sales 
----------------
 (22,270.6)
(1 row)

pgsql=#
复制代码

也可以采用别的名称:

复制代码
pgsql=# CREATE FUNCTION extended_sales(p_itemno int)
pgsql-# RETURNS TABLE(tmp_quantity int, tmp_total numeric) AS $$
pgsql$# BEGIN
pgsql$#   RETURN QUERY SELECT quantity AS tmp_quantity, quantity * price AS tmp_total 
pgsql$#     FROM sales
pgsql$#         WHERE itemno = p_itemno;
pgsql$# END;
pgsql$# $$ LANGUAGE plpgsql;
CREATE FUNCTION
pgsql=# 
pgsql=# select extended_sales(101);
 extended_sales 
----------------
 (22,270.6)
(1 row)

pgsql=# 
复制代码







目录
相关文章
|
2月前
|
关系型数据库 MySQL
【问题处理】—— Mysql : You can‘t specify target table for update in FROM clause
【问题处理】—— Mysql : You can‘t specify target table for update in FROM clause
67 1
|
10月前
|
SQL 关系型数据库 MySQL
MySQL:The used SELECT statements have a different number of columns
执行SQL报错:The used SELECT statements have a different number of columns
366 0
MySQL:The used SELECT statements have a different number of columns
|
11月前
|
SQL 关系型数据库 MySQL
mysql操作中 出现You can‘t specify target table for update in FROM clause错误的解决方法
这个错误实际上也不能称之为咱们sql语句写的不行,实际上是我们在一些细节上没有遵循mysql的语法规范。 问题所在:我们一个sql语句中先select这个表,然后再update这个表的内容。 错误示范: UPDATE StuCose SET Grade=60 WHERE Sno IN( SELECT Sno FROM stucose WHERE Grade<=ALL( SELECT MIN(Grade) FROM stucos
176 0
mysql操作中 出现You can‘t specify target table for update in FROM clause错误的解决方法
|
SQL 关系型数据库 MySQL
mysql的FIND_IN_SET group_concat 函数
mysql的FIND_IN_SET group_concat 函数
177 0
|
SQL Oracle 关系型数据库
MySQL 语法问题:You can‘t specify target table ‘xxx‘ for update in FROM clause. 原因及解决方法
MySQL 语法问题:You can‘t specify target table ‘xxx‘ for update in FROM clause. 原因及解决方法
133 0