Procedure Oracle return query lines

Asked

Viewed 13,534 times

2

I have the following table:

CREATE TABLE CARRO (
    CD_CARRO INT
    ,DONO    VARCHAR(20) 
    ,MARCA   VARCHAR2(20)
);

The Inserts

INSERT INTO CARRO VALUES (1,'VICENTE','FERRARI');
INSERT INTO CARRO VALUES (2,'CARLOS','FUSCA');
INSERT INTO CARRO VALUES (3,'MAIZA','DOBLO');
INSERT INTO CARRO VALUES (4,'FERNANDA','FUSCA');
INSERT INTO CARRO VALUES (5,'BRUNA','FERRARI');

I have an appointment:

SELECT * FROM carro WHERE marca = 'volks';

I would like, from a previous, return to the above query

CREATE PROCEDURE prc_carros (dsmarca VARCHAR2) IS
BEGIN
   SELECT * FROM carro WHERE marca = dsmarca;
END;

I would like you to return the result as if it were a normal table

  • What you can do in the oracle is return a cursor, with the result of your select, or create a function that works like a table, if it suits you I can post an explanation of how to do

  • good still could not do either of the two rs

1 answer

2


In the Oracle you can’t return a select directly through a Procedure, what you can do is return a cursor to Procedure or create a Function and use it as a table.

Using Function:

First you need to create your own return type with all the columns you want to return

CREATE OR REPLACE TYPE OUTPUT_CARRO_TYPE
IS OBJECT (
    MARCA VARCHAR(20),
    DONO VARCHAR2(20)
);

CREATE OR REPLACE TYPE OUTPUT_CARRO
AS TABLE OF OUTPUT_CARRO_TYPE

Then you can create your Function using this type of feedback that you have just created.

CREATE OR REPLACE FUNCTION fn_carros (dsmarca VARCHAR2)
RETURN OUTPUT_CARRO PIPELINED
IS            
BEGIN
    FOR RECORD_OUTPUT IN (
        SELECT * FROM carro WHERE marca = dsmarca
    )
    LOOP
        PIPE ROW (OUTPUT_CARRO_TYPE(RECORD_OUTPUT.MARCA, RECORD_OUTPUT.DONO));
    END LOOP;                   
END;

You can use the Function as follows:

SELECT * FROM TABLE(fn_carros('BMW'));

Using Procedure and Cursor

First you create your Procedure with an out variable that will be your cursor.

create procedure prc_carros (dsmarca VARCHAR2, prc out sys_refcursor)
is
begin
    open prc for SELECT * FROM carro WHERE marca = dsmarca;
end;

To check your result for example you can use the following command:

var rc refcursor;
execute myproc('BMW', :rc);

print rc;
  • then it would return a string only?

  • not it will come back everything you want, just need to adjust the new type you created and on line PIPE ROW (OUTPUT_CARRO_TYPE(RECORD_OUTPUT.marca,RECORD_OUTPUT.COL2)); to add these fields

  • I tried following the example in PL/SQL but at run time it says the function is in invalid state

  • this error happened when you tried to run the SELECT * FROM TABLE(fn_carros('BMW')); ?

  • Yes, when it comes time to call the consultation

  • enter this room http://chat.stackexchange.com/rooms/56238/room-duvida-93568

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.