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.

11 comments on “Oracle Stored Procedure SELECT INTO example

  1. 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?

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

    Reply
    1. 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;

      Reply
  3. This helps me too much

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

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

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

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *