存储过程以在PL / SQL中显示表中的所有记录

时间:2018-05-03 18:37:42

标签: plsql

我真的需要你的帮助。我试图在PL / SQL中创建一个存储过程来按位置计算学生

我已经使用Cursor完成了它,即使它可能听起来很愚蠢。我不知道使用存储过程来做到这一点。 所以这是我用来按位置使用游标

计算学生的代码

//使用光标按位置计算的代码

declare
s_location VARCHAR(15);
cnt NUMBER;
CURSOR curlocation IS
SELECT address,COUNT(address) AS cnt
FROM student
GROUP BY address;
BEGIN
OPEN curlocation;
LOOP
FETCH curlocation INTO s_location,cnt;
EXIT WHEN curlocation%NOTFOUND;
IF cnt=0 THEN
dbms_output.put_line('No Students For'||s_location);
ELSE
dbms_output.put_line('--------------------------------------------');
dbms_output.put_line(cnt ||'  '||'Students For '|| s_location);
END IF;
END LOOP;
CLOSE curlocation;
END;

您可以想象输出类似于::

1名学生......

2名学生......

5名学生......

所以我想使用存储过程做这样的事情。

谢谢guyz

2 个答案:

答案 0 :(得分:1)

您可以像以前一样创建一个过程并使用光标:

create procedure count_and_print_students as
  l_location varchar(15);
  l_count number;

  cursor c_student_locations
  is
    select address, count(address) as cnt
    from student group by address;
begin
  open c_student_locations;
  loop
    fetch c_student_locations into l_location, l_count;
    exit
  when c_student_locations%notfound;
    if l_count = 0  then
      dbms_output.put_line('No Students For'||l_location);
    else
      dbms_output.put_line('--------------------------------------------');
      dbms_output.put_line(l_count ||'  '||'Students For '|| l_location);
    end if;
  end loop;
  close c_student_locations;
end;

并将其运行为:

DECLARE
BEGIN
count_and_print_students();
END;

此外,您可以创建将每个地点的学生作为参数计算的程序,如下所示:

create procedure count_students_per_location(p_location in varchar2, x_count out number) as
begin
  select count(address) 
  into x_count
  from student
  where address = p_location;
end;

因此,它可以按以下方式使用:

DECLARE
  l_count number;
BEGIN
  count_students_per_location('LOCATION_X',l_count);
  dbms_output.put_line(l_count ||'  '||'Students For LOCATION_X');
END;

答案 1 :(得分:0)

创建一个返回单个OUT值的过程没什么意义。这应该是一个功能:

CREATE OR REPLACE FUNCTION student_count_per_location (p_location IN VARCHAR2)
   RETURN NUMBER
   AUTHID DEFINER
AS
   x_count   NUMBER;
BEGIN
   SELECT COUNT (address)
     INTO x_count
     FROM student
    WHERE address = p_location;

   RETURN x_count;
END;
/

BEGIN
   DBMS_OUTPUT.put_line (
         student_count_per_location ('LOCATION X')
      || '  '
      || 'Students For LOCATION_X');
END;
/