Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch MULTIPLE ROWS and STORE in 1 VARIABLE - ORACLE STORED PROCEDURE

I am working on ORACLE STORED PROCEDURES and I have a doubt. I have a query which fetches more than 1 row and I want to store all those 3 row's values in 1 Variable. Can anybody please help me with this.

My QUERY goes like this :

SELECT STUDENT_NAME FROM STUDENT.STUDENT_DETAILS WHERE CLASS_ID= 'C';

Here this query fetches 3 names

Jack, Jill, Bunny

I want all those 3 names to be stored in 1 variable i.e C_NAMES. And after that I am using that variable in further steps of my procedure.

Can anyone please help me with this.

I would highly appreciate your time and effort.

Thanks in advance,

Vrinda :)

like image 452
vrivrivri Avatar asked Jun 06 '13 16:06

vrivrivri


People also ask

How can I pass multiple values to a single variable in Oracle?

create procedure sp1 (p1 in varchar2) as begin select proc_id from proc_tbl where proc_id in (p1); end; The user expects to input multiple values separate by comma or space such as a1, b2, c3 in p1. All the PROC_ID stored in proc_tbl are in upper case.

How do I store multiple rows in PL SQL?

The Oracle INSERT ALL statement is used to add multiple rows with a single INSERT statement. The rows can be inserted into one table or multiple tables using only one SQL command.

What is one of the usual approaches to fetch multiple rows?

Table created. It's the simplest and most efficient way to fetch multiple rows from a dynamically-constructed SELECT.


2 Answers

CREATE PROCEDURE a_proc
AS
    CURSOR names_cur IS
        SELECT  student_name
        FROM    student.student_details
        WHERE   class_id = 'C';

    names_t  names_cur%ROWTYPE;
    TYPE names_ntt IS TABLE OF names_t%TYPE; -- must use type
    l_names  names_ntt;
BEGIN
    OPEN  names_cur;
    FETCH names_cur BULK COLLECT INTO l_names;
    CLOSE names_cur;

    FOR indx IN 1..l_names.COUNT LOOP
        DBMS_OUTPUT.PUT_LINE(l_names(indx).student_name);
    END LOOP;
END a_proc;
like image 121
the_slk Avatar answered Nov 08 '22 21:11

the_slk


Depending on your Oracle version(>= 11G(11.2)), you can use LISTAGG:

SELECT LISTAGG(STUDENT_NAME,',')  WITHIN GROUP (ORDER BY STUDENT_NAME)
FROM STUDENT.STUDENT_DETAILS
WHERE CLASS_ID= 'C';

EDIT: If your Oracle version is inferior to 11G(11.2), take a look here

like image 40
Ederson Avatar answered Nov 08 '22 20:11

Ederson