I would like to create a function in PL/SQL that returns the number of males and females in the database. I created a function which returns the number of either males or females in the database, but not both. This is the code I used.
This is the the code I used to create the function:
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;
The code I used to call it:
declare
c number(2);
begin
c:=totalstudent();
dbms_output.put_line('Total Number of Male is'||c);
end;
/
Here is the
result produced
Briefly, I want a function which will do what that function does but also display the number of Female entries... Both Female and Male entries are in the Database.
I'm not sure what your requirements are. I suggest using an input parameter:
-- These are the codes I used to create the function
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;
Regards
Related
My code:
create table info(str varchar2(30));
declare
cursor c(job emp_ast.job_id%type, dep emp_ast.department_id%type) is select employee_id
from emp_ast
where job_id=job and department_id=dep;
type t_job is table of emp_ast.job_id%type;
t t_job:=t_job();
emp emp_ast.employee_id%type;
i number(3);
begin
select job_id
bulk collect into t
from emp_ast;
for i in 10..270 loop
for j in 1..t.count loop
open c(i, t(j));
loop
fetch c into emp;
insert into info
values (i||' '||t(j)||' '||emp);
exit when c%notfound;
end loop;
i:=i+10;
end loop;
end loop;
end;
/
I get "expression 'I' cannot be used as an assignment target", reffering to the line where I increment i by 10. I am trying to save the department_id, employee_id and job_id as a string in a table for each department and each job.
At the point where you get that message, i refers to the loop control variable i defined in the line for i in 10..270 loop, not the int(3) variable defined earlier. In PL/SQL a loop definition defines a variable which is only accessible inside the loop, and which you cannot alter. I suggest you change the name of one or the other to make them unique.
EDIT
PL/SQL doesn't provide a way to step by more than 1 in a computed FOR loop. Instead, you will need to compute the desired department number value within the loop:
DECLARE
CURSOR c(job EMP_AST.JOB_ID%TYPE,
dep EMP_AST.DEPARTMENT_ID%TYPE)
IS SELECT EMPLOYEE_ID
FROM EMP_AST
WHERE JOB_ID = job AND
DEPARTMENT_ID = dep;
TYPE t_job IS TABLE OF EMP_AST.JOB_ID%TYPE;
t t_job := t_job();
emp EMP_AST.EMPLOYEE_ID%TYPE;
nDepartment NUMBER;
BEGIN
SELECT job_id
BULK COLLECT INTO t
FROM EMP_AST;
FOR i IN 1..27 LOOP
nDepartment := i * 10;
FOR j IN 1..t.COUNT LOOP
OPEN c(t(j), nDepartment);
LOOP
FETCH c INTO emp;
INSERT INTO info
VALUES (nDepartment || ' ' || t(j) || ' ' || emp);
EXIT WHEN c%notfound;
END LOOP; -- cursor c
CLOSE c;
END LOOP; -- j
END LOOP; -- i
END;
/
Note that in the code above the nDepartment value is computed within the i loop, which now increments from 1 to 27 instead of going from 10 to 270.
I am trying to create a small database of bank employees using method in oracle 11g, so at the end I can fetch values of those employees who are entitle for the awards at the end of the year:
Gold medals for employees who have been working at the bank for more than 12 years and supervised more than 6 staff; silver medals for employees who have been working at the bank for more than 8 years and supervised more than 3 staff; bronze medals for employees who have been working at the bank for
more than 4 years, displaying their names and Medal awarded (only
displaying those who have been awarded).
So here what I am doing
create type EmployeeName as object(
title varchar2(10),
firstName varchar2(20),
surname varchar2(20))
not final
/
create or replace type employeeaward as object(
empID integer,
eName EmployeeName,
number_staff_supervised int,
working_years int,
MEMBER FUNCTION award_given RETURN STRING,
MEMBER FUNCTION number_fraction (N real) RETURN real
);
/
CREATE OR REPLACE TYPE BODY employeeaward AS
MEMBER FUNCTION award_given RETURN STRING IS
BEGIN
IF self.working_years > 12 THEN
RETURN 'gold medal';
ELSIF self.working_years > 8 THEN
RETURN 'silver medal';
ELSIF self.working_years > 4 THEN
RETURN 'bronze medals';
END IF;
END award_given;
MEMBER FUNCTION number_fraction(N real) RETURN real IS
num real;
BEGIN
num :=(self.number_staff_supervised);
return num;
END number_fraction;
END;
and then create a table employeeawardtable of employeeaward like this:
create table employeeawardtable of employeeaward;
/
Then insert some values in the table
insert into employeeawardtable values('2001',EmployeeName('Mr','Rohit','Sharma'),'12','18');
/
insert into employeeawardtable values('2002',EmployeeName('Mr','Andrew','Darson'),'9','7');
/
insert into employeeawardtable values('2003',EmployeeName('Mrs','Sarah','Barlow'),'5','4');
/
insert into employeeawardtable values('2004',EmployeeName('Mr','Ram','Gopal'),'11','9');
/
**This is the SQL query, I am struggling to fetch data. **
select e.ename.firstname, e.award_given(),e.number_fraction(15)
from employeeawardtable e
where e.number_fraction() > 8;
Thanks.
Following are the issues with your code.
The number_fraction member function is invoked without a parameter in the predicate. This will throw an error, "ORA-06553: PLS-306: wrong number or types of arguments in call to 'NUMBER_FRACTION'"
Below is SQL for your requirement.
select e.ename.firstname, e.award_given()
from employeeawardtable e
where e.award_given() = 'gold medal' and e.number_staff_supervised > 6
or e.award_given() = 'silver medal' and e.number_staff_supervised > 3
or e.award_given() = 'bronze medal';
The member_function award_given is not returning a default value. This will throw an error. "ORA-06503: PL/SQL: Function returned without value". Fix the type body as below.
CREATE OR REPLACE TYPE BODY employeeaward AS
MEMBER FUNCTION award_given RETURN STRING IS
BEGIN
IF self.working_years > 12 THEN
RETURN 'gold medal';
ELSIF self.working_years > 8 THEN
RETURN 'silver medal';
ELSIF self.working_years > 4 THEN
RETURN 'bronze medals';
ELSE--newly added
RETURN 'no medal';--newly added
END IF;
END award_given;
MEMBER FUNCTION number_fraction(N real) RETURN real IS
num real;
BEGIN
num :=(self.number_staff_supervised);
return num;
END number_fraction;
END;
Now issue the SQL.
Output:
ENAME.FIRSTNAME E.AWARD_GIVEN()
Rohit gold medal
Ram silver medal
I have three PLSQL functions: A, B and C.
The idea is this: C is calling B, B is calling A.
Function A, when it's called by B, returns a numeric value as a status indicator AND a ref cursor with tabular results.
E.g. function_A (A1 in varchar2, A2 out sys_refcursor) return number;
Function B, when it receives the results from A, is expected to reformat the results before passes them on to C, also in a form of a ref cursor.
A is an existing function and it cannot be amended, while B and C will be completely new functions.
The question is, how do I fetch the ref cursor from A? I was able to get the numeric value returned by the function (i.e the status indicator), but I have problem fetching the results of the ref cursor from A.
If I'm calling A from B, can I assume that the ref cursor of A is automatically opened?
What are the logical steps to get the results from A's ref cursor? E.g. can I fetch the results into an object type?
P/S. I have very limited programming experience and am only few months new in PLSQL.
Any hints will be much appreciated.
Since you have not given us the code functions, we will be based on the description of your functions.
According to the description, you have 3 functions:
Function A.
create or replace function A(A1 in varchar2, A2 out sys_refcursor) return number is
begin
open A2 for select 1 from dual;
return 2;
end;
Function B.
create or replace function B(B1 out sys_refcursor) return number is
cur sys_refcursor;
res_A number;
row_ your_table_a%rowtype;
begin
res_A := A('',cur);
loop
fetch cur into row_;
exit when cur%notfound;
--proccess with row A
end loop;
open B1 for select 2 from dual;
return 1;
end;
Function C
create or replace function C() return number is
res_B number;
cur sys_refcursor;
row_ your_table_b%rowtype;
begin
res_B:= B(cur);
loop
fetch cur into row_;
exit when cur%notfound;
--proccess with row B
end loop;
return 2;
end;
Maybe you can try the below snippet. Tried to replicate the scenario you mentioned in the question. Hope this helps.
CREATE OR REPLACE FUNCTION A_TEST(
A1 IN VARCHAR2,
A2 OUT sys_refcursor )
RETURN NUMBER
AS
lv_num PLS_INTEGER;
BEGIN
NULL;
OPEN a2 FOR SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 19;
RETURN 1;
END;
CREATE OR REPLACE FUNCTION B_TEST
RETURN sys_refcursor
AS
lv_cur sys_refcursor;
lv_num PLS_INTEGER;
BEGIN
lv_num:=A_TEST('AV',lv_cur);
RETURN lv_cur;
END;
CREATE OR REPLACE FUNCTION C_TEST
RETURN sys_refcursor
AS
tab PLS_INTEGER;
lv_cur sys_refcursor;
BEGIN
lv_cur:=B_TEST;
LOOP
FETCH lv_cur INTO tab;
EXIT
WHEN lv_cur%NOTFOUND;
dbms_output.put_line(tab);
END LOOP;
END;
i have student and trainer tables :
student table:
student_id (primary key)
name
email
trainer table:
trainer_id
student_id
amount
output has to:
sid name email amount
22 ram r#g 200
34 sam r#f
i want to get (student_id,name,email) from student table and (amount) from trainer table(imp : trainer_id and student_id should match(like sid = 46,tid =78,amount=500) then only the amount has to display value. otherwise amount will display empty but (student_id,name,email) should display)
in trainer table, student_id and trainer_id has to match...based on that amount will come..i mean if we send the select query as "select amount from trainer where student_id= 20 and trainer_id=36...". that column should match for sid and tid
If you do it this way, It wil not show data if amount is empty :
select st.student_id,
st.name,
st.email,
tt.amount
from student_table st, trainer_table tt
where st.student_id = tt.student_id
NVL function lets you substitute a value when a null value is encountered,
so if you do it this way, It wil show data and show 0 instead of null:
select st.student_id,
st.name,
st.email,
(nvl(select tt.amount
from trainer_table tt
where st.student_id = tt.student_id,0))) amount
from student_table st
This can be accomplished with PLSQL. Sorry it is so extensive but I hope it allows you to see the power of PLSQL if you need to manipulate data based on conditionals.
DECLARE
TYPE result_record IS RECORD
( sid NUMBER
, name VARCHAR2(60)
, email VARCHAR2(60)
, amount NUMBER);
CURSOR c IS select st.student_id sid,
st.name name,
st.email email,
tt.amount amount
from student_table st, trainer_table tt
where st.student_id = tt.student_id;
TYPE results_table IS TABLE OF results_record INDEX BY BINARY_INTEGER;
c_rec c%ROWTYPE;
temp_rec RESULTS_RECORD;
results RESULTS_TABLE;
lv_index NUMBER := 0;
BEGIN
OPEN c;
WHILE lv_index <= c%ROWCOUNT LOOP
FETCH c INTO c_rec;
temp_rec.sid := c_rec.sid;
temp_rec.name := c_rec.name;
temp_rec.email := c_rec.email;
temp_rec.amount := c_rec.amount;
results(lv_index) := temp_rec;
lv_index := lv_index + 1;
END LOOP;
CLOSE c;
-- Now we can access and modify our table from inside PLSQL
SELECT * FROM results;
-- Use PLSQL logic to make the table output pretty with '$' and conditionals
FOR i IN results LOOP
dbms_output.put_line(i.sid||' $'||i.amount); -- example for how to access
-- your code here
END LOOP;
END;
/
As always, I hope this gives you some ideas.
-V
IN my oracle database i want to create a function or procedure with cursor which will use dynamic table name.here is my code.
CREATE OR REPLACE Function Findposition ( model_in IN varchar2,model_id IN number) RETURN number IS cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber FROM '||model_in;
FOR employee_rec in c2
LOOP
IF employee_rec.id=model_id then
cnumber :=employee_rec.rownumber;
end if;
END LOOP;
close c2;
RETURN cnumber;
END;
help me to solve this problem.IN
There is no need to declare a c1 type for a weakly typed ref cursor. You can just use the SYS_REFCURSOR type.
You can't mix implicit and explicit cursor calls like this. If you are going to OPEN a cursor, you have to FETCH from it in a loop and you have to CLOSE it. You can't OPEN and CLOSE it but then fetch from it in an implicit cursor loop.
You'll have to declare a variable (or variables) to fetch the data into. I declared a record type and an instance of that record but you could just as easily declare two local variables and FETCH into those variables.
ROWID is a reserved word so I used ROWPOS instead.
Putting that together, you can write something like
SQL> ed
Wrote file afiedt.buf
1 CREATE OR REPLACE Function Findposition (
2 model_in IN varchar2,
3 model_id IN number)
4 RETURN number
5 IS
6 cnumber number;
7 c2 sys_refcursor;
8 type result_rec is record (
9 id number,
10 rowpos number
11 );
12 l_result_rec result_rec;
13 BEGIN
14 open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rowpos FROM '||model_in;
15 loop
16 fetch c2 into l_result_rec;
17 exit when c2%notfound;
18 IF l_result_rec.id=model_id
19 then
20 cnumber :=l_result_rec.rowpos;
21 end if;
22 END LOOP;
23 close c2;
24 RETURN cnumber;
25* END;
SQL> /
Function created.
I believe this returns the result you expect
SQL> create table foo( id number );
Table created.
SQL> insert into foo
2 select level * 2
3 from dual
4 connect by level <= 10;
10 rows created.
SQL> select findposition( 'FOO', 8 )
2 from dual;
FINDPOSITION('FOO',8)
---------------------
4
Note that from an efficiency standpoint, you'd be much better off writing this as a single SQL statement rather than opening a cursor and fetching every row from the table every time. If you are determined to use a cursor, you'd want to exit the cursor when you've found the row you're interested in rather than continuing to fetch every row from the table.
From a code clarity standpoint, many of your variable names and data types seem rather odd. Your parameter names seem poorly chosen-- I would not expect model_in to be the name of the input table, for example. Declaring a cursor named c2 is also problematic since it is very non-descriptive.
You can do this, you don't need loop when you are using dynamic query
CREATE OR REPLACE Function Findposition(model_in IN varchar2,model_id IN number)
RETURN number IS
cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT rownumber
FROM (
SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber
FROM '||model_in || '
) WHERE id = ' || model_id;
FETCH c2 INTO cnumber;
close c2;
return cnumber;
END;