I want to fetch limited no. of rows using refcursor. then I need to update same set of records. is it possible?
create or replace PROCEDURE myproc (
P_ROWCOUNT IN NUMBER,
OUT_TXN_IDS OUT OF_CR_TYPE,
P_CD_ERROR OUT NUMBER,
P_DS_ERROR OUT VARCHAR2
)
AS
V_TXNID NUMBER;
BEGIN
P_CD_ERROR := 0;
P_DS_ERROR := 'SUCCESS';
OPEN OUT_TXN_IDS for
SELECT id FROM table1 WHERE status='N' AND ROWNUM<=P_ROWCOUNT;
EXCEPTION
WHEN OTHERS THEN
P_CD_ERROR := sqlcode;
P_DS_ERROR := 'WF-ERROR - myproc - ' || substr(SQLERRM, 1, 200);
RETURN;
END myproc;
I need to update same records to status Y after refcursor returns. can we do this. please suggest
I don't have your tables nor data so I simplified it a little bit, but - it should work nonetheless.
Initial statuses:
SQL> SELECT status, count(*) FROM table1 group by status;
S COUNT(*)
- ----------
Y 7
N 7
Procedure: basically, you'd modify rows represented by ID returned by ref cursor.
SQL> DECLARE
2 out_txn_ids SYS_REFCURSOR;
3 p_rowcount NUMBER := 5;
4 l_id table1.id%TYPE;
5 BEGIN
6 OPEN out_txn_ids FOR SELECT id
7 FROM table1
8 WHERE status = 'N'
9 AND ROWNUM <= p_rowcount;
10
11 LOOP
12 FETCH out_txn_ids INTO l_id;
13
14 EXIT WHEN out_txn_ids%NOTFOUND;
15
16 UPDATE table1
17 SET status = 'Y'
18 WHERE id = l_id;
19 END LOOP;
20
21 CLOSE out_txn_ids;
22 END;
23 /
PL/SQL procedure successfully completed.
Result:
SQL> SELECT status, count(*) FROM table1 group by status;
S COUNT(*)
- ----------
Y 12
N 2
SQL>
Related
DECLARE
TYPE norollno IS TABLE OF VARCHAR2(100);
rollno norollno;
BEGIN
BEGIN
SELECT token
BULK COLLECT INTO rollno
FROM tableA
WHERE columname='rollnoofstud';
EXCEPTION
WHEN NO_DATA_FOUND THEN
rollno := norollno();
END ;
IF rollno >0 THEN
FOR i IN rollno.FIRST..norollno.LAST
LOOP
<doSomeThing>
END LOOP;
END IF;
END;
I am trying this but I am not getting output. I doubt if my select statement is correct.
I don't have your table so I created one:
SQL> CREATE TABLE tablea
2 AS
3 SELECT ename AS token, 'rollnoofstud' AS columname
4 FROM emp
5 WHERE deptno = 10;
Table created.
Code you posted isn't that wrong; requires a little bit of fixing (see line #17, the way you check whether collection contains something (count it!); typo in FOR loop):
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 TYPE norollno IS TABLE OF VARCHAR2 (100);
3
4 rollno norollno;
5 BEGIN
6 BEGIN
7 SELECT token
8 BULK COLLECT INTO rollno
9 FROM tableA
10 WHERE columname = 'rollnoofstud';
11 EXCEPTION
12 WHEN NO_DATA_FOUND
13 THEN
14 rollno := norollno ();
15 END;
16
17 IF rollno.COUNT > 0
18 THEN
19 FOR i IN rollno.FIRST .. rollno.LAST
20 LOOP
21 DBMS_OUTPUT.put_line (rollno (i));
22 END LOOP;
23 END IF;
24 END;
25 /
CLARK --> here's the result
KING
MILLER
PL/SQL procedure successfully completed.
SQL>
[EDIT: with your sample table and data:]
(note that there's no text datatype in Oracle!)
SQL> CREATE TABLE students
2 (
3 rollnostud INTEGER PRIMARY KEY,
4 name VARCHAR2 (10) NOT NULL,
5 gender VARCHAR2 (1) NOT NULL
6 );
Table created.
SQL> INSERT INTO students
2 VALUES (1, 'Ryan', 'M');
1 row created.
SQL> INSERT INTO students
2 VALUES (2, 'Joanna', 'F');
1 row created.
SQL> INSERT INTO students
2 VALUES (3, 'John', 'M');
1 row created.
Procedure:
SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
2 TYPE norollno IS TABLE OF VARCHAR2 (100);
3
4 rollno norollno;
5 BEGIN
6 BEGIN
7 SELECT name
8 BULK COLLECT INTO rollno
9 FROM students;
10 EXCEPTION
11 WHEN NO_DATA_FOUND
12 THEN
13 rollno := norollno ();
14 END;
15
16 IF rollno.COUNT > 0
17 THEN
18 FOR i IN rollno.FIRST .. rollno.LAST
19 LOOP
20 DBMS_OUTPUT.put_line (rollno (i));
21 END LOOP;
22 END IF;
23 END;
24 /
Ryan
Joanna
John
PL/SQL procedure successfully completed.
SQL>
CREATE TABLE test_table
(
col1 NUMBER(10),
col2 NUMBER(10)
);
INSERT INTO test_table
VALUES (1, 2);
I am writing a stored procedure wherein if I give a table name as an input, that should give me the table data and column details.
For example:
SELECT *
FROM <input_table_name>;
But this causes an error that the SQL command has not ended properly even though I have taken care of this.
My attempt:
CREATE OR REPLACE PROCEDURE sp_test(iv_table_name IN VARCHAR2,
p_out_cur OUT SYS_REFCURSOR)
AS
lv_str VARCHAR2(400);
lv_count NUMBER(1);
lv_table_name VARCHAR2(255):=UPPER(iv_table_name);
BEGIN
lv_str := 'SELECT * FROM '||lv_table_name;
SELECT COUNT(1) INTO lv_count FROM all_tables WHERE table_name = lv_table_name;
IF lv_count = 0 THEN
dbms_output.put_line('Table does not exist');
ELSE
OPEN p_out_cur FOR lv_str;
END IF;
END sp_test;
Tool used: SQL developer(18c)
In dynamic SQL, you do NOT terminate statement with a semicolon.
EXECUTE IMMEDIATE 'SELECT * FROM '||lv_table_name||';';
-----
remove this
Anyway, you won't get any result when you run that piece of code. If you really want to see table's contents, you'll have to switch to something else, e.g. create a function that returns ref cursor.
Sample data:
SQL> SELECT * FROM test_table;
COL1 COL2
---------- ----------
1 2
3 4
Procedure you wrote is now correct:
SQL> CREATE OR REPLACE PROCEDURE sp_test (iv_table_name IN VARCHAR2,
2 p_out_cur OUT SYS_REFCURSOR)
3 AS
4 lv_str VARCHAR2 (400);
5 lv_count NUMBER (1);
6 lv_table_name VARCHAR2 (255) := UPPER (iv_table_name);
7 BEGIN
8 lv_str := 'SELECT * FROM ' || lv_table_name;
9
10 SELECT COUNT (1)
11 INTO lv_count
12 FROM all_tables
13 WHERE table_name = lv_table_name;
14
15 IF lv_count = 0
16 THEN
17 DBMS_OUTPUT.put_line ('Table does not exist');
18 ELSE
19 OPEN p_out_cur FOR lv_str;
20 END IF;
21 END sp_test;
22 /
Procedure created.
Testing:
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 l_rc SYS_REFCURSOR;
3 l_col1 NUMBER (10);
4 l_col2 NUMBER (10);
5 BEGIN
6 sp_test ('TEST_TABLE', l_rc);
7
8 LOOP
9 FETCH l_rc INTO l_col1, l_col2;
10
11 EXIT WHEN l_rc%NOTFOUND;
12
13 DBMS_OUTPUT.put_line (l_col1 || ', ' || l_col2);
14 END LOOP;
15 END;
16 /
1, 2 --> contents of the
3, 4 --> TEST_TABLE
PL/SQL procedure successfully completed.
SQL>
A function (instead of a procedure with the OUT parameter):
SQL> CREATE OR REPLACE FUNCTION sf_test (iv_table_name IN VARCHAR2)
2 RETURN SYS_REFCURSOR
3 AS
4 lv_str VARCHAR2 (400);
5 lv_count NUMBER (1);
6 lv_table_name VARCHAR2 (255) := UPPER (iv_table_name);
7 l_rc SYS_REFCURSOR;
8 BEGIN
9 lv_str := 'SELECT * FROM ' || lv_table_name;
10
11 SELECT COUNT (1)
12 INTO lv_count
13 FROM all_tables
14 WHERE table_name = lv_table_name;
15
16 IF lv_count = 0
17 THEN
18 raise_application_error (-20000, 'Table does not exist');
19 ELSE
20 OPEN l_rc FOR lv_str;
21 END IF;
22
23 RETURN l_rc;
24 END sf_test;
25 /
Function created.
Testing:
SQL> SELECT sf_test ('liksajfla') FROM DUAL;
SELECT sf_test ('liksajfla') FROM DUAL
*
ERROR at line 1:
ORA-20000: Table does not exist
ORA-06512: at "SCOTT.SF_TEST", line 18
SQL> SELECT sf_test ('TEST_TABLE') FROM DUAL;
SF_TEST('TEST_TABLE'
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
COL1 COL2
---------- ----------
1 2
3 4
SQL>
I have a procedure that deletes the data from table1. Five instances of the procedure running the same time and all ran without any error/exception.
But still, there are many records in the table1 where EndTime <= v_purgedate. Please help.
declare
rowcount1 NUMBER;
begin
LOOP
delete table1 eh
where eh.EndTime <= v_purgedate
and rownum <= 30000 ;
rowcount1 := rowcount1 + sql%rowcount;
commit;
exit when rowcount1=0;
rowcount1=0;
END LOOP;
end;
/
You are trying to do what is called "do it yourself parallelism", as opposed to the parallel processing that Oracle can do by itself if you ask nicely.
There is a package called DBMS_PARALLEL_EXECUTE that does this for you. You split the data into chunks (based on ROWIDs or numbers), then call the RUN_TASK procedure to process each chunk, either serially or in parallel. There is one commit per chunk.
Here is a demonstration that deletes 30,000 rows per commit. First, test data:
SQL> create table table1(endtime) as
2 select trunc(sysdate) - level/24 from dual
3 connect by level <= 240000;
Table TABLE1 created.
SQL> insert into table1 select * from table1;
240,000 rows inserted.
SQL> insert into table1 select * from table1;
480,000 rows inserted.
SQL> insert into table1 select * from table1;
960,000 rows inserted.
SQL> select count(*) from table1;
COUNT(*)
----------
1920000
Now, here is the code:
SQL> declare
2 l_task_name varchar2(128) := 'Delete_TABLE1';
3 l_sql_chunk clob := q'§
4 select date '2100-01-01' - min(endtime) start_id,
5 date '2100-01-01' - max(endtime) end_id,
6 chunk
7 from (
8 select endtime,
9 ceil(row_number() over(order by endtime) / 30000) chunk
10 from table1 where endtime < sysdate - 8000
11 )
12 group by chunk
13 §';
14 l_sql_run clob := q'§
15 delete from table1
16 where endtime between
17 date '2100-01-01' - :start_id and
18 date '2100-01-01' - :end_id
19 §';
20 l_boolean boolean := false;
21 task_not_found EXCEPTION;
22 PRAGMA EXCEPTION_INIT(task_not_found, -29498);
23 begin
24 begin
25 DBMS_PARALLEL_EXECUTE.DROP_TASK (l_task_name);
26 exception when task_not_found then null;
27 end;
28 DBMS_PARALLEL_EXECUTE.CREATE_TASK (l_task_name);
29 DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_SQL (
30 task_name => l_task_name,
31 sql_stmt => l_sql_chunk,
32 by_rowid => l_boolean
33 );
34 DBMS_PARALLEL_EXECUTE.RUN_TASK (
35 task_name => l_task_name,
36 sql_stmt => l_sql_run,
37 language_flag => 1,
38 parallel_level => 0 -- 0 for serial, 2+ for parallel
39 );
40 end;
41 /
you have an endless Loop, because rowcount1 will never be 0 when your table contains data that will be deleted.
i think what you what is
declare
rowcount1 NUMBER;
begin
LOOP
delete table1 eh
where eh.EndTime <= v_purgedate -- you should also initialize a variable
and rownum <= 30000 ;
--rowcount1 := rowcount1 + sql%rowcount;
commit;
exit when sql%rowcount = 0;
rowcount1=0;
END LOOP;
end;
/
When you declare the variable rowcount1, you do not assign any number to it, so its value is NULL. Afterwards, when you add a number to NULL the result is always NULL. This is surely not what you want. To illustrate:
SQL> declare
2 rowcount1 NUMBER;
3 begin
4 dbms_output.put_line('<'||rowcount1||'>');
5 rowcount1 := rowcount1 + 1;
6 dbms_output.put_line('<'||rowcount1||'>');
7 end;
8 /
<>
<>
PL/SQL procedure successfully completed.
It seems your code will go in an endless loop. You say that is not the case, so clearly you are not showing us any real code.
Anyway, this is not a good way to do what you want. I'll post another answer saying why.
Regards, Stew Ashton
It's a easy code for delete data in a table .
Try it.
declare
cursor c is
select * from table1 where rownum<=30000;
begin
for i in c loop
delete from table1 where EndTime <= v_purgedate;
end loop;
commit;
end;
I've two cursors both have almost similar code just a little difference in the group by condition, I want if the id is 1 or 2 e.t.c then it should open cur1 else cur2, basically one cursor at a time. Is there any possibility of achieving this?
if id in (1,2,3,4) then
cursor_value:= 'cur1';
else
cursor_value := 'cur2';
end if;
for i in cursor_value loop
end loop;
You can use an OPEN-FOR statement. Example:
DECLARE
TYPE EmpCurTyp IS REF CURSOR;
v_emp_cursor EmpCurTyp;
emp_record employees%ROWTYPE;
v_stmt_str VARCHAR2(200);
v_e_job employees.job%TYPE;
BEGIN
-- Dynamic SQL statement with placeholder:
v_stmt_str := 'SELECT * FROM employees WHERE job_id = :j';
-- Open cursor & specify bind argument in USING clause:
OPEN v_emp_cursor FOR v_stmt_str USING 'MANAGER';
-- Fetch rows from result set one at a time:
LOOP
FETCH v_emp_cursor INTO emp_record;
EXIT WHEN v_emp_cursor%NOTFOUND;
END LOOP;
-- Close cursor:
CLOSE v_emp_cursor;
END;
/
One option would be to include both cursor's SELECT statements into cursor FOR loop, along with a condition that chooses which one of them will be used. For example:
SQL> declare
2 id number := &par_id;
3 begin
4 for cur_r in (select * from emp
5 where deptno = 10
6 and id in (1,2,3,4)
7 union all
8 select * from emp
9 where deptno = 20
10 and id not in (1,2,3,4)
11 )
12 loop
13 dbms_output.put_Line(cur_r.deptno ||' '||cur_r.ename);
14 end loop;
15 end;
16 /
Enter value for par_id: 1 --> ID = 1, so use SELECT for DEPTNO = 10
old 2: id number := &par_id;
new 2: id number := 1;
10 CLARK
10 KING
10 MILLER
PL/SQL procedure successfully completed.
SQL> /
Enter value for par_id: 823 --> ID <> 1, so use SELECT for DEPTNO = 20
old 2: id number := &par_id;
new 2: id number := 823;
20 SMITH
20 JONES
20 SCOTT
20 ADAMS
20 FORD
PL/SQL procedure successfully completed.
SQL>
The simple way could be to use if else condition.
DECLARE
type cur REF CURSOR;
c cur;
BEGIN
IF id in (1,2,3,4) THEN
OPEN c FOR 'cursor query 1';
ELSE
OPEN c FOR 'cursor query 2';
END IF ;
END;
Cheers!!
I have a file which consists of thousand rows and I need to get a portion of the 2nd row (about 50 characters) and the last row of the file. Please advise. Thank you.
Im trying to do something like UTL_FILE.READLINE(fileloc, filename, nrow, lastrow).
SAMPLE:
Filename: CLOSED_SO_20190124.txt
DATA in the FILE:
0246608377|22795124004|
650930363|1-8IGO3S82920|
0245563264|22669075004|
0245563264|22669075004|
164260364|1-2DFE-6573219|
650821459|1-6HWQUF11209|
EXPECTED OUTPUT:
650930363|1-8IGO3S82920|
650821459|1-6HWQUF11209|
Here's an example.
Directory name & its location, as well as sample file contents:
SQL> select directory_name, directory_path from all_directories;
DIRECTORY_NAME DIRECTORY_PATH
------------------------------ --------------------
EXT_DIR c:\temp
SQL> $type c:\temp\sofile.txt
0246608377|22795124004|
650930363|1-8IGO3S82920|
0245563264|22669075004|
0245563264|22669075004|
164260364|1-2DFE-6573219|
650821459|1-6HWQUF11209|
SQL>
The procedure: a local counter (l_cnt) knows line number; if it is equal to 2, display that line. Also, when nothing's being found (so exception handler section is executed), I've reached the end of the file so I'm displaying the last line as well.
SQL> set serveroutput on
SQL>
SQL> declare
2 l_file utl_file.file_type;
3 l_dir varchar2(20) := 'EXT_DIR';
4 l_name varchar2(20) := 'sofile.txt';
5 l_line varchar2(50);
6 l_cnt number := 0;
7 begin
8 l_file := utl_file.fopen (l_dir, l_name, 'R');
9 loop
10 begin
11 utl_file.get_line(l_file, l_line);
12 l_cnt := l_cnt + 1;
13 if l_cnt = 2 then
14 dbms_output.put_line('2nd : ' || l_line);
15 end if;
16 exception
17 when no_data_found then
18 dbms_output.put_line('last: ' || l_line);
19 exit;
20 end;
21 end loop;
22 utl_file.fclose(l_file);
23 end;
24 /
2nd : 650930363|1-8IGO3S82920|
last: 650821459|1-6HWQUF11209|
PL/SQL procedure successfully completed.
SQL>
In Oracle 11g
select col
from
(
select
rownum AS rnum,
LEFT(myCol, 50) col
from Table1
where Rownum < 3
)
WHERE rnum = 2
In Oracle 12c
select LEFT(mycol, 50) col
from Table1
ORDER BY val
OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;
For the last row
select LEFT(mycol, 50) col
from my_table
where pk = ( select max(pk) from my_table )
then you can union them