I have a table called stud_ans_sheet
.
I want to run a loop which would every time fetch next values from table.
It's a PL/SQL program and I am doing it with a cursor. This is my program, but it has a lot of errors:
set serveroutput on;
declare
cursor c_stud is select stud_no,ans from stud_ans_sheet;
v_stud c_stud%rowtype;
v_no stud_ans_sheet.stud_no%type;
answer varchar(10);
i number(3);
v_corr stud_ans_sheet.corr_ans%type;
v_wrong stud_ans_sheet.wrong_ans%type;
v_unattempt stud_ans_sheet.unattempt_ans%type;
score number(5,2);
v_ans varchar(10);
str1 varchar(40);
str2 varchar(40);
nval stud_ans_sheet.stud_no%type;
total number(5,2);
begin
answer:='AACCABAABD';
open c_stud;
loop
fetch c_stud into v_stud;
exit when c_stud%notfound;
for i in 1..10
loop
nval:= select seq.nextval from stud_ans_sheet.stud_no;
select stud_no,ans into v_no,v_ans from stud_ans_sheet where stud_no=nval;
str2:=substr(v_ans,i,1);
str1:=substr(answer,i,1);
if(str2=str1) then
update stud_ans_sheet
set corr_ans=v_corr+1;
elsif(str2='E') then
update stud_ans_sheet
set unattempt_ans=v_unattempt+1;
else
update stud_ans_sheet
set wrong_ans=v_wrong+1;
end if;
end loop;
update stud_ans_sheet
set score=corr_ans-wrong_ans*0.25+unattempt_ans;
end loop;
close c_stud;
end;
/
I have changed some of your code, try this:
SET SERVEROUTPUT ON;
DECLARE
ANSWER VARCHAR (10);
V_CORR STUD_ANS_SHEET.CORR_ANS%TYPE;
V_WRONG STUD_ANS_SHEET.WRONG_ANS%TYPE;
V_UNATTEMPT STUD_ANS_SHEET.UNATTEMPT_ANS%TYPE;
STR1 VARCHAR (40);
STR2 VARCHAR (40);
BEGIN
ANSWER := 'AACCABAABD';
FOR R_STUD IN (SELECT STUD_NO, ANS
FROM STUD_ANS_SHEET)
LOOP
V_CORR := 0;--It's better to have only one update
V_WRONG := 0;
V_UNATTEMPT := 0;
FOR I IN 1 .. 10
LOOP
STR2 := SUBSTR (R_STUD.ANS, I, 1);
STR1 := SUBSTR (ANSWER, I, 1);
IF (STR2 = STR1)
THEN
V_CORR := V_CORR + 1;
ELSIF (STR2 = 'E')
THEN
V_UNATTEMPT := V_UNATTEMPT + 1;
ELSE
V_WRONG := V_WRONG + 1;
END IF;
END LOOP;
UPDATE STUD_ANS_SHEET
SET SCORE = V_CORR- V_WRONG* 0.25 + V_UNATTEMPT,
CORR_ANS = V_CORR,
WRONG_ANS = V_WRONG,
UNATTEMPT_ANS = V_UNATTEMPT
WHERE R_STUD.STUD_NO = STUD_NO;
END LOOP;
END;
/