我有一个称为电话簿的表,它有两列(firstName, LastName)
。我想使用光标通过firstName创建一个lastName索引表,并编写了以下代码:
CREATE OR REPLACE PROCEDURE proc1 AS
TYPE tableNames IS TABLE OF VARCHAR2(20) INDEX BY VARCHAR(20);
v1 tableNames;
v_firstName PHONEBOOK.FIRSTNAME%TYPE;
v_lastName PHONEBOOK.LASTNAME%TYPE;
CURSOR c_name IS SELECT FIRSTNAME, LASTNAME FROM PHONEBOOK;
BEGIN
OPEN c_name;
LOOP
FETCH c_name INTO v_firstName, v_lastName;
EXIT WHEN c_name%NOTFOUND;
v1(v_firstName) := v_lastName;
END LOOP;
FOR idx IN v1.FIRST..v1.LAST
LOOP
DBMS_OUTPUT.PUT_LINE (v1(idx));
END LOOP;
CLOSE c_name;
END;
/
已成功编译。当我运行此过程时,它应该打印存储在tableNames中的lastNames,但它给了我一个错误:
ORA-06502“ PL / SQL:数字或值错误”
原因:算术,数字,字符串,转换或约束错误 发生。例如,如果尝试执行以下操作,则会发生此错误 将值NULL分配给声明为NOT NULL的变量,或者 尝试将大于99的整数分配给变量 声明为NUMBER(2)。
操作:更改数据,如何操作或如何声明数据 值不违反约束条件。
请帮助我解决这个问题
答案 0 :(得分:1)
不是FOR
,而是WHILE
。另外,我将游标FOR
循环用作 source ;易于编写和维护。
SQL> create table phonebook (firstname varchar2(10), lastname varchar2(10));
Table created.
SQL> insert into phonebook
2 select 'Little', 'Foot' from dual union all
3 select 'Mc' , 'Donalds' from dual;
2 rows created.
SQL> create or replace procedure proc1 as
2 type tablenames is table of varchar2(10) index by varchar2(10);
3 v1 tablenames;
4 idx varchar2(10);
5 begin
6 for cur_r in (select firstname, lastname
7 from phonebook
8 )
9 loop
10 v1(cur_r.firstname) := cur_r.lastname;
11 end loop;
12
13 idx := v1.first;
14 while idx is not null loop
15 dbms_output.put_line(v1(idx));
16 idx := v1.next(idx);
17 end loop;
18 end;
19 /
Procedure created.
SQL> exec proc1;
Foot
Donalds
PL/SQL procedure successfully completed.
SQL>