首页 > 解决方案 > 使用 pl/sql 中的函数计算男女学生

问题描述

我想在 PL/SQL 中创建一个函数,它返回数据库中男性和女性的数量。我创建了一个函数,它返回数据库中男性或女性的数量,但不能同时返回两者。这是我使用的代码。

这是我用来创建函数的代码:

create or replace function totalstudent
return number is
total_male number(2):=0;
begin
select count(*) into total_male from New_Student where gender='Male';
return total_male;
end;

我用来调用它的代码:

declare 
c number(2);
begin
c:=totalstudent();
dbms_output.put_line('Total Number of Male is'||c);
end;
/

这是 产生的结果

简而言之,我想要一个函数,它可以执行该函数的功能,但也显示女性条目的数量......女性和男性条目都在数据库中。

标签: plsql

解决方案


我不确定你的要求是什么。我建议使用输入参数:

-- 这些是我用来创建函数的代码

CREATE OR REPLACE FUNCTION totalstudent (v_gender IN VARCHAR2)
    RETURN NUMBER
IS
    total_gender   NUMBER (2) := 0;
BEGIN
    SELECT COUNT (*)
      INTO total_gender
      FROM New_Student
     WHERE gender = v_gender;

    RETURN total_gender;
END;

-- The code I used to call it

DECLARE
    c   NUMBER (2);
BEGIN
    c := totalstudent ('Male');
    DBMS_OUTPUT.put_line ('Total Number of Male is' || c);
    c := totalstudent ('Female');
    DBMS_OUTPUT.put_line ('Total Number of Female is' || c);
END;

问候


推荐阅读