HI am new to stored procedure. Am using a dynamic sql with
select * from table into var
var is a variable.the var contains more than one value ,when i try to run the proc with inputs i get an error:
ORA-01422: exact fetch returns more than requested number of rows
Is there a way such that the var开发者_如何学编程iable can hold more than one row using dynamic sql.
Use collection variables:
DECLARE
TYPE tt_int IS TABLE OF INTEGER;
var tt_int;
BEGIN
SELECT id
BULK COLLECT
INTO var
FROM table;
END;
You have to bulk collect
the result set into a table of
type if you're going to select multiple rows.
declare
type record_type is table of <table_name>;
var_records record_type;
begin
select *
bulk collect into var_records
from <table_name>;
end;
/
See also my answer to PL SQL how to select all columns
you can also return the results to a ref cursor
set serveroutput on
DECLARE
REFEXAMPLE SYS_REFCURSOR;
VAR NUMBER ;
col varchar2(50);
BEGIN
OPEN REFEXAMPLE FOR --Here you open the cursor and fill it
SELECT *
FROM (
SELECT 1 VAR, 'a' COL FROM DUAL
UNION ALL
SELECT 2 VAR, 'b' COL FROM DUAL
UNION ALL
SELECT 3 VAR, 'c' COL FROM DUAL
UNION ALL
SELECT 4 VAR, 'd' COL FROM DUAL
UNION ALL
SELECT 5 VAR, 'e' COL FROM DUAL
) EXAMPLETABLE ;
DBMS_OUTPUT.PUT_LINE('var ' || 'col');
DBMS_OUTPUT.PUT_LINE('---------');
LOOP
FETCH REFEXAMPLE INTO VAR, col; --now loop through
EXIT WHEN REFEXAMPLE%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(var || ' ' || col || ' ');
END LOOP;
CLOSE REFEXAMPLE;
end ;
/
var col
---------
1 a
2 b
3 c
4 D
5 e
You can use a table variable, which provides you with an in-memory table of your results. You declare a table variable similar to a standard variable:
declare @MyVar table (col1 col1type, col2 col2type, etc.)
精彩评论