简体   繁体   中英

Insert different record in table using FOR loop by PL/SQL

I want to insert data in the table in that way, so that whenever command runs, different data is entered. like,

create table oppo
(
name varchar(10),
class varchar(10),
roll number (5)
);
declare
s number;
i number;
n char(10);
c char(10);
r number;
begin
s:=:no_of_records;
for i in 1..s LOOP
n:=:Enter_Name;
c:=:Enter_Class;
r:=:Enter_Roll;
insert into oppo (name,class,roll) values (n,c,r);
END LOOP;
End; 

when i run the program, and enter no_of_records (5 or any number), and entering name and other data. As a result the same data is displayed 5 times (or number of times record entered). I want to enter unique data every 5 times.

PL/SQL procedures aren't interactive . If you want to insert different values, replace this anonymous PL/SQL block with a stored procedure and run it as many times as you want, providing new values every time.

For example:

SQL> create table test (name varchar2(20), class number);

Table created.

SQL> create or replace procedure p_test (par_name in varchar2, par_class in number) as
  2  begin
  3    insert into test (name, class) values (par_name, par_class);
  4  end;
  5  /

Procedure created.

SQL> exec p_test('&name', &class);
Enter value for name: LF
Enter value for class: 1

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Bigfoot
Enter value for class: 2

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Scott
Enter value for class: 3

PL/SQL procedure successfully completed.

SQL> select * From test;

NAME                      CLASS
-------------------- ----------
LF                            1
Bigfoot                       2
Scott                         3

SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM