我正在研究一个不太难的SQL函数:它需要一些参数来查找表中的特定课程,计算该课程中有多少人,将其与课程的最大容量,并根据需要返回1或0:
drop function if exists room_for_more_students(the_class_name varchar, the_semester_code int);
create function room_for_more_students(the_class_name varchar, the_semester_code int)
returns int as $BODY$
begin
select * from class_offerings as match_table
where class_name = the_class_name and semester_code = the_semester_code;
select count(student_id) from match_table as num_students_in_class;
select avg(maximum_capacity) from match_table as num_students_allowed_in_class;
--These will all be the same so "avg" just means "the maximum capacity for the class"
if num_students_in_class < num_students_allowed_in_class then return 1;
else return 0;
end if;
end
$BODY$
language plpgsql;
这似乎并非真的应该是所有复杂的实现,并且该函数创建没有问题,但每次我尝试通过psycopg2调用它时我收到:
ProgrammingError: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead
我尝试过尝试使用PERFORM,但我尝试的任何组合似乎要么保持相同的问题,要么创建一系列新的问题。我也对此做了一些研究,因为还有一些关于同一问题的其他帖子,但大多数时候答案似乎是用户没有添加特定的返回语句,我有。我完全没有想法,并且会感谢任何可能的投入。
答案 0 :(得分:1)
对于您的情况,您必须声明一些变量并为其分配查询结果。如果不将结果分配给任何地方,则无法运行查询。
我更新你的功能如下:
drop function if exists room_for_more_students(the_class_name varchar, the_semester_code int); create function room_for_more_students(the_class_name varchar, the_semester_code int) returns int as $BODY$ DECLARE num_students_allowed_in_class numeric; num_students_in_class numeric; begin WITH match_table AS ( select * from class_offerings where class_name = the_class_name and semester_code = the_semester_code ) select count(student_id), avg(maximum_capacity) INTO num_students_in_class, num_students_allowed_in_class from match_table; if num_students_in_class
希望它符合您的要求!