[英]fetching table data into a table using cursor
I have a table called phonebook and it has two columns (firstName, LastName)
. 我有一个名为phonebook的表,它有两列
(firstName, LastName)
。 I want to create a table of lastName index by firstName using cursor, and I wrote this code: 我想使用光标通过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;
/
It has been successfully compiled. 已成功编译。 When I run this procedure it should print lastNames which stored in the tableNames but it gave me an error:
当我运行此过程时,它应该打印存储在tableNames中的lastNames,但它给了我一个错误:
ORA-06502 "PL/SQL: numeric or value error"
ORA-06502“ PL / SQL:数字或值错误”
Cause: An arithmetic, numeric, string, conversion, or constraint error occurred.原因:发生算术,数字,字符串,转换或约束错误。 For example, this error occurs if an attempt is made to assign the value NULL to a variable declared NOT NULL, or if an attempt is made to assign an integer larger than 99 to a variable declared NUMBER(2).
例如,如果尝试将值NULL分配给声明为NOT NULL的变量,或者试图将大于99的整数分配给声明的NUMBER(2),则会发生此错误。
Action: Change the data, how it is manipulated, or how it is declared so that values do not violate constraints.行动:更改数据,如何操作或声明数据,以使值不违反约束。
Please help me to solve this problem 请帮我解决这个问题
Not FOR
, but WHILE
. 不是
FOR
而是WHILE
。 Also, I used cursor FOR
loop as a source ; 另外,我使用了游标
FOR
循环作为源 ; easier to write & maintain. 易于编写和维护。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.