PL / SQL将多个varchar2选择为一个varchar2

时间:2014-11-13 09:01:23

标签: oracle plsql varchar2

我是pl-sql的初学者,我正在尝试编写函数代码来读取coursename并显示讲义名称,coursename以及与coursename匹配的标题。

然而,我无法得到一个不错的输出,无论我尝试过的不同方法,并且我得到了相当多的不同错误,目前下面是能够编译但没有给出任何结果的代码。

任何人都可以帮我解决这个问题并告诉我哪里出错了吗?

Set echo on

set serveroutput on

CREATE OR REPLACE FUNCTION Courses(coursename IN VARCHAR2) RETURN VARCHAR2

IS
    results VARCHAR2(100);
    l VARCHAR2(30);
    c VARCHAR2(30);
    t VARCHAR2(30);

BEGIN

    FOR course IN(select lecturerName, coursename, title into l,c,t  from course where Coursename = coursename)

LOOP
    results := results || l || c || t;
END LOOP;


RETURN results;

END Courses;
/

SELECT Courses('SQL') from dual;


Courses('SQL')

2 个答案:

答案 0 :(得分:1)

如果您希望函数根据课程名称返回所有匹配项,则结果将类似于表。我猜你不想要返回1场比赛,你的桌子上可能会有更多。此外,您可能不希望将所有匹配视为一行,即所有匹配合并在一起。

为此,您需要一个管道函数,它返回一个由自定义类型表示的数据集。

首先,创建TYPE:

CREATE OR REPLACE TYPE COURSEINFO as Table of VARCHAR2(512); --size can vary based on your needs

该功能变为:

CREATE OR REPLACE FUNCTION COURSES (
   p_coursename   IN VARCHAR2)
   RETURN COURSEINFO
   PIPELINED
IS
   text      VARCHAR2 (512);
BEGIN
   FOR course IN (SELECT lecturerName, coursename, title
                    FROM course
                   WHERE Coursename = p_coursename)
   LOOP
      text := course.lecturerName || ', ' || course.coursename || ', ' || course.title;

    PIPE ROW(text);
   END LOOP;

   RETURN;
END COURSES;

对于输入表:

course1 | title2 | lecturer3
course1 | title1 | lecturer1
course2 | title2 | lecturer2

和查询:

select COLUMN_VALUE as COURSE_INFO from table(COURSES('course1')); 

产生输出:

lecturer1, course1, title1
lecturer3, course1, title2

答案 1 :(得分:0)

一定是这个

FOR course IN (select lecturerName, coursename, title from course where Coursename = coursename) 

LOOP
    results := results || course.lecturerName || course.coursename || course.title;
END LOOP;

或者更简单

select lecturerName||coursename||title||
from course 
where Coursename = 'SQL';