Declare cursor in sqlplus command mode - oracle

I have an SQL file which uses declares a cursor and I am running it using #abc, but it did not execute all statements and waiting without returning to command prompt. It did not proceed after declare cursor statement. When I tried to run the declare cursor statement in command mode, the same problem is happening again. I am able to return to SQL priompt only after pressing Ctrl + C. I am very new to SQL world. Though this could be a basic mistake, I am not able to find out the solution in any site. Any help is greatly appreciated.
SQL> DECLARE CURSOR id_cursor IS SELECT id FROM user_names WHERE dept_no = 1002
AND BITAND(flags, 4) = 4 AND time_created BETWEEN 1137974400 AND 1326067199;
2
3
4 ;
5
6

All DECLARE and BEGIN blocks in SQL*Plus need to be ended with a / on a new empty line:
SQL> DECLARE
2 CURSOR c IS SELECT 1 FROM DUAL;
3 BEGIN
4 NULL;
5 END;
6 /
PL/SQL procedure successfully completed.
Without this / SQL*Plus has no way to know that your statement has ended (so in your example it waits for user input).

After the ; type a / and enter. This will run your PL/SQL statement. But the sample you've given does nothing but declare a cursor. You must then use it like so:
declare
cursor ID_CURSOR is
select ID
from USER_NAMES
where DEPT_NO = 1002
and bitand(FLAGS, 4) = 4
and TIME_CREATED between 1137974400 and 1326067199;
begin
for REC in ID_CURSOL loop
<do something with your data>;
end loop;
end;
/

Related

Oracle Cursor, No Data Found exception

I'm trying to modify a procedure that removes a user from the system, adding a bit that generates a list of any areas over which they are the only admin. I have read that cursors can work when 0 results are found, so I am assuming that my query is the problem. Tables 1 (A) and 2 (B&C) are joined by the primary key of table A. Subquery B is a list of all the areas a user is admin over, and Subquery C is a list of all areas with only one admin. In the specific instance I'm testing, there is no matching area_id between subqueries B and C. Is there a way I can modify this query to work properly? I tried moving the opening of the cursor behind an if statement, but still receive the error, so I'm assuming it's the declaration of the cursor that is resulting in the exception being thrown.
CURSOR AA_CUR IS
SELECT AREA_NAME
FROM FILE_TRANSFER.AREA_LU A,
(SELECT AREA_ID
FROM FILE_TRANSFER.USER_AREA_ACCESS
WHERE AREA_ADMIN='Y'
AND USERNAME IN (SELECT USERNAME
FROM FILE_TRANSFER.USER_INFORMATION
WHERE USER_INFORMATION_ID = v_UIID)) B,
(SELECT AREA_ID, AREA_ADMIN, COUNT(*)
FROM FILE_TRANSFER.USER_AREA_ACCESS
WHERE AREA_ADMIN='Y'
HAVING COUNT(*) = 1
GROUP BY AREA_ID, AREA_ADMIN) C
WHERE A.AREA_ID = B.AREA_ID
AND B.AREA_ID = C.AREA_ID;
Your assumption is wrong.
Cursor's SELECT can't return NO_DATA_FOUND. If it returns nothing, it is silently ignored, nothing happens.
SQL> declare
2 cursor c1 is
3 select 'x' from dual
4 where 1 = 2; -- this query returns "nothing"
5 c1r c1%rowtype;
6 begin
7 open c1;
8 fetch c1 into c1r;
9 close c1;
10 end;
11 /
PL/SQL procedure successfully completed.
See? Nothing happened. Just to show that query will raise NO_DATA_FOUND (if ran separately):
SQL> declare
2 l_val varchar2(1);
3 begin
4 select 'x' into l_val from dual
5 where 1 = 2; -- this will raise NO_DATA_FOUND
6 end;
7 /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
SQL>
Therefore, there must be some other SELECT statement that is raising that error. Which one? Can't tell as you didn't post much of your code and - even if you did - without your tables and data it would be difficult to guess.
So, what to do? Debug your code. A simple option is to put DBMS_OUTPUT.PUT_LINE calls between every two statements so that you'd see which part of code actually failed - then you'll be able to try to fix it.

PL/SQL IF statement and variable declaration

I am trying to make the code posted below work, but I am receiving an error about the IF statement:
DECLARE
a number;
BEGIN
SELECT Pers_API.Is_Manager_(10018) INTO a from dual;
EXCEPTION
WHEN no_data_found THEN a := 0;
END;
IF (a >0) THEN
SELECT 1 from dual;
ELSE
SELECT 0 from dual;
END IF;
In the first block I am declaring an 'A' variable and setting it to 0 (by the way, the API call result will be 0 or 1, nothing else). The first block works fine or - at least - I do think so. But the IF block is not working and having this error:
PLS-00103:Encountered the symbol "IF"
Any help is appreciated.
Update: I have tried it this way:
DECLARE
a number:=0;
BEGIN
SELECT Pers_API.Is_Manager_(10018) INTO a from dual;
IF (:a >0) THEN
SELECT 1 from dual;
ELSE
SELECT 0 from dual;
END IF;
END;
I received the exception below:
ORA-01008: not all variables bound
Update
In other words, what I am trying to do is:
if Pers_API.Is_Manager_(10018) returns true (as 1), I have to do another select statement
if it's false (as 0), I have to return null.
Any other ideas are appreciated.
A few objections, if I may.
there's no need to select from dual in order to assign a value to a variable, when that value is returned by a function - simply assign it
exception handler seems to be superfluous. You said that the is_manager_ function returns 0 or 1 and nothing else. Therefore, it'll always return something, so - why do you expect that SELECT to return NO_DATA_FOUND? Besides, such a case should be handled by the function itself (i.e. you have to make sure that it returns 0 or 1 and nothing else)
the last paragraph you wrote is somewhat strange. You said that - if the function returns 1, you have to run another SELECT statement. Otherwise, you have to return null (while code you wrote, select 0 ... suggests a zero (0), not null); so, which one is true?
also, saying that you have to return something (null, 0, whatever) suggests that piece of code you wrote should be a function that returns a value. Is that so?
Code that actually compiles might look like in this example.
First, a function (based on Scott's schema) that checks whether an employee is a manager:
SQL> create or replace function is_manager_ (par_empno in number)
2 return number
3 is
4 /* function checks whether PAR_EMPNO belongs to a manager and returns:
5 - 1 - employee is a manager
6 - 0 - employee is NOT a manager
7 */
8 retval number := 0;
9 begin
10 select max(1)
11 into retval
12 from emp e
13 where mgr = par_empno;
14
15 return retval;
16 exception
17 when no_data_found then
18 return retval;
19 end;
20 /
Function created.
SQL>
Code you posted, rewritten so that it does something:
if an employee is a manager, returns his/her salary
otherwise, it does not
SQL> declare
2 a number := is_manager_(&&l_empno);
3 l_sal emp.sal%type;
4 begin
5 if a > 0 then
6 select sal
7 into l_sal
8 from emp
9 where empno = &&l_empno;
10 dbms_output.put_line('Employee is a manager and his/her salary is ' || l_sal);
11 else
12 null;
13 dbms_output.put_line('Employee is not a manager');
14 end if;
15 end;
16 /
Enter value for l_empno: 7698
Employee is a manager and his/her salary is 2850
PL/SQL procedure successfully completed.
SQL> undefine l_empno
SQL> /
Enter value for l_empno: 7369
Employee is not a manager
PL/SQL procedure successfully completed.
SQL> undefine l_empno
SQL> /
Enter value for l_empno: -1
Employee is not a manager
PL/SQL procedure successfully completed.
SQL>
See if you can adjust it so that it fits your needs. If not, do answer to my objections posted at the beginning of this message, and we'll see what to do next.
It appears to me that what you are really trying to achieve here is to run a query which must use the result obtained from the package function as a condition. If so, the PL/SQL block wouldn't be needed and can be written as a basic select operation.
What is still not clear from your explanation is whether your select query
SELECT 1 from dual is the actual query you are about to use in your code.Generally, in the select statement, we use CASE expression to evaluate the conditional logic, which essentially does what IF ELSE condition was supposed to do to return the desired result.The query would have a structure of this form,
SELECT
CASE
WHEN pers_api.is_manager_(10018) = 1 THEN some_expression
ELSE some_other_expression --If you omit the else condition, it defaults to null when all others are false
END
END
as
FROM DUAL;
More specifically, if you want to have the resultant expression come from another database table, the queries can take the form
SELECT
CASE
WHEN pers_api.is_manager_(10018) = 1 THEN some_expression
ELSE some_other_expression --If you omit the else condition, it defaults to null when all others are false
END
as
FROM table_to_run_query
WHERE where_clauses = some_values;
If you say that your resultant expression from the table involves many other constructs, the challenge would be to compose it in a single query cleverly to avoid any PL/SQL at all. That would be achievable, but it will require that you explain us with some sample data and expected result, as to what exactly you want,preferably in a new question.
It would not be complete if I don't mention the REFCURSOR technique to obtain results from a select query in PL/SQL. It is either through DBMS_SQL.RETURN_RESULT(Oracle 12c and above) or using a REFCURSOR bind variable running it in SQL* Plus or as Script in other tools (F5).
VARIABLE x refcursor;
DECLARE BEGIN
IF
pers_api.is_manager_(10018) = 1
THEN
OPEN :x FOR SELECT some_columns FROM some_tables;
ELSE
OPEN :x FOR SELECT some_columns FROM other_tables;
END IF;
--DBMS_SQL.RETURN_RESULT(:x); --12c and above
END;
/
PRINT x -- 11g

Oracle Sqlplus calling sql script repeatedly in a loop

Is it possible to call a script inside a loop via sqlplus?
Suppose we have two files simple_sample.sql and main.sql:
|simple_sample.sql|
PROMPT HELLO &1
-------------------
|main.sql|
begin
for loop_parameter in 1..3 loop
#magic_call# #simple_sample.sql loop_parameter
end loop;
end;
/
What can be used instead of #magic_call# to obtain this output:
sqlplus user/password#schema #main.sql
HELLO 1
HELLO 2
HELLO 3
===PL/SQL===
1.1
You can call another script from PL/SQL but it will be inlined in the code and must be correct PL/SQL snippet.
So if we modify original scripts
simple_sample1.sql
dbms_output.put_line(&1);
main.sql
begin
for loop_parameter in 1..3 loop
#simple_sample1.sql loop_parameter
end loop;
end;
/
Then result is following
SQL> #main
old 3: dbms_output.put_line(&1);
new 3: dbms_output.put_line(loop_parameter);
1
2
3
PL/SQL procedure successfully completed.
Of course, inlined code may look almost like standalone block if you wrap it with "begin" and "end".
begin
dbms_output.put_line(&1);
end;
1.2 If you want to run arbitrary script from PL/SQL you can run sqlplus from PL/SQL code using DBMS_SCHEDULER... but it's a bit weird, isn't it? I hope it's needless to say that script will be executed in another session created by DBMS_SCHEDULER.
===SQL===
2. You can inline code into SQL as well, but, again, query must compile after inlining.
hello.sql
'HELLO' || ' ' ||
SQL> select
2 #hello.sql
3 rownum
4 from dual
5 connect by rownum <= 3;
HELLO 1
HELLO 2
HELLO 3
SQL>
SQL> select
2 #START hello.sql
3 rownum
4 from dual
5 connect by rownum <= 3;
HELLO 1
HELLO 2
HELLO 3
===SPOOL===
3. Finally, you can generate in a loop what you need, spool it and execute it.
You can use either SQL or PL/SQL to generate the script. Example below shows SQL approach.
main_spool.sql
set echo off;
set pagesize 0;
spool tmp.sql
select
'#simple_sample.sql' || ' ' || rownum x
from dual
connect by rownum <= 3;
spool off
#tmp.sql
SQL> #main_spool
#simple_sample.sql 1
#simple_sample.sql 2
#simple_sample.sql 3
HELLO 1
HELLO 2
HELLO 3

PL/SQL set a link as default at the begining of the script

I need to select a link at the beginning in the script. Usually we do select links as below,
begin
select * from v$database#linkname;
end;
But now I need to select the link at the beginning something like this,
begin
select_link 'linkname';
select * from v$database;
end;
Thank you!
select * from v$database#linkname;
You cannot simply have a SELECT statement like that in PL/SQL. It expects an INTO clause.
If I understand correct;y, you want to parameterize the DATABASE LINK. I am afraid you need to (ab) use dynamic SQL.
For example,
SQL> var cur refcursor
SQL> DECLARE
2 var_link varchar2(20);
3 BEGIN
4 var_link:='#your_db_link';
5 OPEN :cur FOR 'SELECT * FROM dual'||var_link;
6 END;
7 /
PL/SQL procedure successfully completed.
SQL> print cur
D
-
X
SQL>

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

I have this table:
ALLITEMS
---------------
ItemId | Areas
---------------
1 | EAST
2 | EAST
3 | SOUTH
4 | WEST
The DDL:
drop table allitems;
Create Table Allitems(ItemId Int,areas Varchar2(20));
Insert Into Allitems(Itemid,Areas) Values(1,'east');
Insert Into Allitems(ItemId,areas) Values(2,'east');
insert into allitems(ItemId,areas) values(3,'south');
insert into allitems(ItemId,areas) values(4,'east');
In MSSQL, to get a cursor from a dynamic SQL I can do:
DECLARE #v_sqlStatement VARCHAR(2000);
SET #v_Sqlstatement = 'SELECT * FROM ALLITEMS';
EXEC (#v_sqlStatement); --returns a resultset/cursor, just like calling SELECT
In Oracle, I need to use a PL/SQL Block:
SET AUTOPRINT ON;
DECLARE
V_Sqlstatement Varchar2(2000);
outputData SYS_REFCURSOR;
BEGIN
V_Sqlstatement := 'SELECT * FROM ALLITEMS';
OPEN outputData for v_Sqlstatement;
End;
--result is : anonymous block completed
**But all I get is
anonymous block completed".
How do I get it to return the cursor?
(I know that if I do AUTOPRINT, it will print out the information in the REFCURSOR (it's not printing in the code above, but thats another problem))
I will be calling this Dynamic SQL from code (ODBC,C++), and I need it to return a cursor. How?
You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):
CREATE OR REPLACE FUNCTION get_allitems
RETURN SYS_REFCURSOR
AS
my_cursor SYS_REFCURSOR;
BEGIN
OPEN my_cursor FOR SELECT * FROM allitems;
RETURN my_cursor;
END get_allitems;
This will return the cursor.
Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.
If you really need to use dynamic SQL you can put your query in single quotes:
OPEN my_cursor FOR 'SELECT * FROM allitems';
This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.
Make sure to use bind-variables where possible to avoid hard parses:
OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;
in SQL*Plus you could also use a REFCURSOR variable:
SQL> VARIABLE x REFCURSOR
SQL> DECLARE
2 V_Sqlstatement Varchar2(2000);
3 BEGIN
4 V_Sqlstatement := 'SELECT * FROM DUAL';
5 OPEN :x for v_Sqlstatement;
6 End;
7 /
ProcÚdure PL/SQL terminÚe avec succÞs.
SQL> print x;
D
-
X
You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')
like Vincent wrote, you can do something like this:
begin
open :yourCursor
for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
using :someFilterValue;
end;
You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.
Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )
Depending on which access library you use, it might be a royal pain or straight forward.
This setting needs to be set:
SET SERVEROUTPUT ON

Resources