Main Tutorials

Oracle Stored Procedure SELECT INTO example

Here’s a SELECT INTO stored procedure example in Oracle database.

1. Table SQL Script

DBUSER table creation script.


CREATE TABLE DBUSER ( 
  USER_ID       NUMBER (5)    NOT NULL, 
  USERNAME      VARCHAR2 (20)  NOT NULL, 
  CREATED_BY    VARCHAR2 (20)  NOT NULL, 
  CREATED_DATE  DATE          NOT NULL, 
  PRIMARY KEY ( USER_ID ) 
 )

2. Stored Procedure

A stored procedure, uses SELECT INTO mechanism to assign the matched values to OUT parameters.


CREATE OR REPLACE PROCEDURE getDBUSERByUserId(
	   p_userid IN DBUSER.USER_ID%TYPE,
	   o_username OUT DBUSER.USERNAME%TYPE,
	   o_createdby OUT  DBUSER.CREATED_BY%TYPE,
	   o_date OUT DBUSER.CREATED_DATE%TYPE)
IS
BEGIN

  SELECT USERNAME , CREATED_BY, CREATED_DATE
  INTO o_username, o_createdby,  o_date 
  from  DBUSER WHERE USER_ID = p_userid;

END;
/

3. Calls from PL/SQL

Call from PL/SQL like this :


DECLARE
   o_username DBUSER.USERNAME%TYPE;
   o_createdby DBUSER.CREATED_BY%TYPE;
   o_date DBUSER.CREATED_DATE%TYPE;
BEGIN

   getDBUSERByUserId(1001,o_username,o_createdby,o_date);
   
   DBMS_OUTPUT.PUT_LINE('username :  ' || o_username);
   DBMS_OUTPUT.PUT_LINE('createdby :  ' || o_createdby);
   DBMS_OUTPUT.PUT_LINE('createddate :  ' || o_date);
   
END;
/

Result
Record with userId=1001 is displayed via getDBUSERByUserId store procedure.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
11 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
santosh
8 years ago

what if we retrieve data from more than one tables by using joins?

Sergey
6 years ago

Thanks !!!

Raghav
11 years ago

Very useful. Thanks!

i7kkii
4 years ago

uikk

Manickam
5 years ago

after pl/sql successfully completed, how can i view the result for specific empid?

Junrey
5 years ago
Reply to  Manickam

Add “set serveroutput on”

set serveroutput on
DECLARE
o_username DBUSER.USERNAME%TYPE;
o_createdby DBUSER.CREATED_BY%TYPE;
o_date DBUSER.CREATED_DATE%TYPE;
BEGIN

getDBUSERByUserId(1001,o_username,o_createdby,o_date);

DBMS_OUTPUT.PUT_LINE(‘username : ‘ || o_username);
DBMS_OUTPUT.PUT_LINE(‘createdby : ‘ || o_createdby);
DBMS_OUTPUT.PUT_LINE(‘createddate : ‘ || o_date);

END;

Juan
7 years ago

This helps me too much

Do you have any example returning a ref_cursor and executing it with Codefirst EF6 in C#?

DUY
11 years ago

here, because user_id is primary key, return 1 row. if return 2 rows, can you help me?

Mark Thien
11 years ago

as simple as just split the leg then insert !

sam
5 years ago

Hi,
While compiling the code i am getting below error.
Error(2,17): PLS-00201: identifier ‘DBUSER.USER_ID’ must be declared.
how to reslove this?

junrey
5 years ago
Reply to  sam

You should have a DBUSER table with field name user_id