Reputation: 618
I'm new in DBMS_SQL. I'm trying to fetch 1st row from cursor, but nothing is displayed. What I did wrong? Here's a code:
CREATE OR REPLACE PROCEDURE TEST_SQL
IS
id_var NUMBER;
name_var VARCHAR2(30);
sal_var Number;
source_cursor INTEGER;
countp INTEGER;
BEGIN
source_cursor := dbms_sql.open_cursor;
DBMS_SQL.PARSE(source_cursor,
'SELECT employee_id, first_name, salary FROM employees where department_id = 50',
DBMS_SQL.NATIVE);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 1, id_var);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 2, name_var, 30);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 3, sal_var);
countp := DBMS_SQL.EXECUTE(source_cursor);
DBMS_SQL.COLUMN_VALUE(source_cursor, 1, id_var);
DBMS_SQL.COLUMN_VALUE(source_cursor, 2, name_var);
DBMS_SQL.COLUMN_VALUE(source_cursor, 3, sal_var);
dbms_output.put_line('id_var: '||id_var ||', name_var: '||name_var ||', sal_var: '|| sal_var);
END;
/
And output is:
PROCEDURE TEST_SQL compiled
anonymous block completed
id_var: , name_var: , sal_var:
EDIT: school mistake - forgot about Fetch_rows -.- Everything works!
Upvotes: 1
Views: 697
Reputation: 191305
You aren't fetching any data; you need to do:
DBMS_SQL.FETCH_ROWS(source_cursor);
So this works:
CREATE OR REPLACE PROCEDURE TEST_SQL
IS
id_var NUMBER;
name_var VARCHAR2(30);
sal_var Number;
source_cursor INTEGER;
countp INTEGER;
BEGIN
source_cursor := dbms_sql.open_cursor;
DBMS_SQL.PARSE(source_cursor,
'SELECT employee_id, first_name, salary FROM employees where department_id = 50',
DBMS_SQL.NATIVE);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 1, id_var);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 2, name_var, 30);
DBMS_SQL.DEFINE_COLUMN(source_cursor, 3, sal_var);
countp := DBMS_SQL.EXECUTE(source_cursor);
countp := DBMS_SQL.FETCH_ROWS(source_cursor);
DBMS_SQL.COLUMN_VALUE(source_cursor, 1, id_var);
DBMS_SQL.COLUMN_VALUE(source_cursor, 2, name_var);
DBMS_SQL.COLUMN_VALUE(source_cursor, 3, sal_var);
dbms_output.put_line('id_var: '||id_var ||', name_var: '||name_var ||', sal_var: '|| sal_var);
END;
/
set serveroutput on
exec test_sql;
PL/SQL procedure successfully completed.
id_var: 120, name_var: Matthew, sal_var: 8000
Or as Tony Andrews pointed out, combine the two steps with EXECUTE_AND_FETCH
.
Of course, you probably want to do the fetch in a loop, as this will only fetch and display the first row returned by the query.
Upvotes: 1