我正在尝试输出教授教授的课程列表,方法是接收教授的id by参数,并显示所有课程,每门课程用逗号分隔。例如,如果教授教授人文科学和数学,我希望输出为:‘人文科学,科学,数学’。然而,我得到的只是“数学”。它只显示它找到的最后一个与教授id匹配的字段。
CREATE OR REPLACE FUNCTION listar_cursos(prof NUMBER) RETURN VARCHAR
IS
CURSOR C1 IS
SELECT subject.name AS name FROM subject
INNER JOIN course_semester
ON subject.id = course_semester.id_subject
WHERE course_semester.id_profesor = prof
ORDER BY subject.name;
test VARCHAR(500);
BEGIN
FOR item IN C1
LOOP
test:= item.name ||',';
END LOOP;
RETURN test;
END;
/我知道listagg存在,但我不希望使用它。
发布于 2018-08-31 08:08:01
在您的循环中,将重新赋值给test变量,而不是附加到该变量。这就是为什么在循环结束时,它只保存item.name的最后一个值。
相反,赋值应该是这样的
test := test || ',' || item.name另请注意,这将在字符串的开头留下一个逗号。您可能希望返回ltrim(test, ','),而不是返回test。
请注意,您不需要显式声明游标。使用隐式游标的代码更容易阅读(在我看来),如下所示。我创建了示例表和数据来测试函数,然后展示了函数代码以及如何使用它。
create table subject as
select 1 id, 'Humanities' name from dual union all
select 2 , 'Science' from dual union all
select 3 , 'Math' from dual
;
create table course_semester as
select 1 id_subject, 201801 semester, 1002 as id_profesor from dual union all
select 2 , 201702 , 1002 as id_profesor from dual union all
select 3 , 201801 , 1002 as id_profesor from dual
;
CREATE OR REPLACE FUNCTION listar_cursos(prof NUMBER) RETURN VARCHAR IS
test VARCHAR(500);
BEGIN
FOR item IN
(
SELECT subject.name AS name FROM subject
INNER JOIN course_semester
ON subject.id = course_semester.id_subject
WHERE course_semester.id_profesor = prof
ORDER BY subject.name
)
LOOP
test:= test || ',' || item.name;
END LOOP;
RETURN ltrim(test, ',');
END;
/
select listar_cursos(1002) from dual;
LISTAR_CURSOS(1002)
-----------------------
Humanities,Math,Sciencehttps://stackoverflow.com/questions/52106554
复制相似问题