[英]Iterating through select result in PostgreSQL without PL/pgSQL
I am currently working on a system built to handle the different reservations of classes and cubicles in a school building. 我目前正在开发一种系统,用于处理学校建筑物中班级和小隔间的不同保留。 I have it such a way that when you are reserving a classroom you are automatically reserving every cubicle inside of it.
我有这样一种方式,当您预订教室时,您会自动保留其中的每个隔间。
I need to iterate through the result of a select in pure SQL without the use of PL/pgSQL to achieve this reservation as it's not exactly clear how many cubicles a classroom has prior to querying it. 我需要遍历纯SQL中的选择结果而不使用PL / pgSQL来实现此保留,因为尚不清楚在查询之前教室有多少个隔间。
I've already tried PL/pgSQL, and while it does work well, I would need an approach that doesn't use PL/pgSQL for class requirements. 我已经尝试过PL / pgSQL,虽然它可以很好地工作,但我需要一种不使用PL / pgSQL满足类要求的方法。 Here's a sample of my PL/pgSQL implementation with the
FOR
keyword. 这是我的带有
FOR
关键字的PL / pgSQL实现的示例。
CREATE OR REPLACE FUNCTION createReservationClass(p_codeBuilding CHAR(2),p_codeClass INT,p_CIP VARCHAR(8),p_date DATE,p_startPeriod INT,p_endPeriod INT,p_description VARCHAR(1024))
RETURNS VOID
AS $$
FOR temprow IN SELECT CODE_CUBICULE FROM public.CUBICULE where CODE_BUILDING = p_codeBuilding AND CODE_CLASS = p_codeClass
LOOP
SELECT createReservationCubicule(p_codeBuilding, p_codeClass, temprow.CODE_CUBICULE, p_CIP, p_date, p_startPeriod, p_endPeriod, p_description);
END LOOP;
END;
$$
LANGUAGE PLPGSQL;
I'd like it that when I am given a building number and a classroom number, it will automatically reserve every cubicle it also has. 我希望当我获得建筑物号和教室号时,它将自动保留它也有的每个隔间。 I'm not sure if I have the right approach of if there is an easier way to go about it.
我不确定是否有更简便的方法来解决问题。
The only requirement is I am not allowed to use PL/pgSQL to write my function. 唯一的要求是不允许我使用PL / pgSQL编写函数。
Why the weird requirement not to use PL/pgSQL? 为什么奇怪的要求不使用PL / pgSQL? However, you can easily do it with an SQL function.
但是,您可以使用SQL函数轻松完成此操作。
Stop thinking procedurally and start thinking in SQL. 停止过程式思考,开始使用SQL进行思考。 What you want to do can be done with a single query without (explicit) loops:
您可以通过一个查询而无需执行(显式)循环来完成您想做的事情:
SELECT createReservationCubicule(
p_codeBuilding,
p_codeClass,
CODE_CUBICULE,
p_CIP,
p_date,
p_startPeriod
p_endPeriod,
p_description
)
FROM public.CUBICULE
where CODE_BUILDING = p_codeBuilding
AND CODE_CLASS = p_codeClass;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.