I have a procedure in an Oracle database which I use to insert users into a table. But now, I need to implement a loop, so that I use that same procedure to insert many users.
I have little knowledge of pl/sql so I don't know which is the best way to do this. Should I pass the data through a varray?
And if so, how can I implement a loop in my procedure?
CREATE OR REPLACE PROCEDURE insert_users(
p_username IN xx_users.username%TYPE,
p_pass IN xx_users.pass%TYPE,
p_role IN VARCHAR2
)
IS
l_id_role NUMBER;
l_role VARCHAR2(200);
l_user VARCHAR2(200);
l_pass VARCHAR2(200);
BEGIN
l_user := p_user;
l_pass := p_pass;
l_role := p_role;
SELECT id_role
INTO l_id_role
FROM xx_roles
WHERE role_name = l_role;
INSERT INTO xx_users (id_user,
username,
pass,
id_role
) VALUES (xx_users_id.nextval,
l_user,
l_pass,
l_id_role
);
COMMIT;
END;
I was thinking that maybe I could create another procedure which takes an array and for each element, calls the procedure insert_users
but I don't think that is the most effective way to do it.
Best Answer
Suppose you have the xx_roles and xx_users tables, and (instead of an array) a third table new_users, which contains the new users' names and temporary ids, something like :
After executing all the code above, the xx_users table is empty:
Now, you could use a procedure that looks similar to this, utilising an "cursor for loop" (CAUTION: this will need exception handling, eventually!):
Testing:
Update - As @miracle173 has pointed out, it may be a better idea to use a single INSERT in this case. Example: