Use cursor in a select statement - plsql

Hope you can help me, Im trying to use a cursor in a sql query. I'm 99% sure this can be done, so please any suggestions? this is my code
FUNCTION filter (c_cur_trip_menu IN c_menu_tripulantes)
RETURN c_menu_tripulantes IS
BEGIN
SELECT *
FROM c_cur_trip_menu , opciones_migradas
WHERE mnu.mnu_idemnu = id_opcion;
RETURN c_cur_trip_menu;
END filter;
What I want is to use the cursor as a table.
thanks in advance.

You can copy data from cursor to temporary table, but you cant use a cursor like a table. If the function you want to build in oracle you can't use select syntax to display data:
FOR cur in c_cur_trip_menu
LOOP
dbms_output.put_line(cur.col1||' 'cur.col2);
END LOOP;

You can't select from cursor (but you could create cursor from any select statement (using cursor(your query))) but table or pipelined functions could help you with your task. http://www.oracle-base.com/articles/misc/pipelined-table-functions.php helps you. Nevertheless I've never understood trying to move function approach for retrieving data in sql based DB - views solve it perfect. Functions are weak to be estimated by CBO so you create the place to make your queries work slower in advance. What for - no idea....

Related

How to add a date with an INSERT INTO SELECT in PL SQL?

For my homework I need to make a package that contains a procedure that removes all records from the table dwdimartist and then fills the table with all records from the table artist and add a field with the date of today.
This is what I've created, it works but I don't know if it's performant enough. Is it better to use a cursor that loops over each record in the table artist?
CREATE OR REPLACE PACKAGE BODY dwh AS
PROCEDURE filldwh IS
today_date DATE := SYSDATE;
BEGIN
DELETE FROM dwdimartist;
INSERT INTO dwdimartist (artistkey, name) (SELECT artistid, name FROM artist);
UPDATE dwdimartist SET added = today_date;
END filldwh;
END dwh;
Simple SQL query like you did is better choice than a cursor or implicit loop.
possible improvement:
You should do it at once without update: set the date during insert.
INSERT INTO dwdimartist (artistkey, name, added)
(SELECT artistid, name, sysdate FROM artist);
Hope it helps
You don’t need to use cursors. You can hardly beat Insert ... select since it’s SQL itself and in most cases it works better than any programmatic structure due to native dbms optimization. However, you can do better if you decrease number of I/O operations. You don’t need update here. Simply add sysdate to your select and insert everything together.
insert into dwdimartist(artistkey, name, added) select artistid, name, sysdate from artist;
Another thing to improve is your ‘delete’. While it’s small table for learning purposes you won’t feel any difference between delete and truncate but for real ETL tasks and big tables you’ll see it definitely. Yes you cannot use truncate directly in your PL/SQL but there are 3 ways to do it:
execute immediate ‘truncate dwdimartist’;
Dbms_utility.exec_ddl_statement(‘truncate ...;’);
DBMS_SQL package
However, remember that calling truncate will execute commit like any ddl command. So delete may be the only option sometimes. But even if it is, you should avoid it for the whole table.

Teradata For Loop without Cursor

How to define FOR LOOP without Cursor in Teradata?
Actually I'm having code like this:
CREATE PROCEDURE TEST1()
BEGIN
DECLARE VAR1 VARCAHR(200);
DECLARE VAR2 VARCAHR(200);
FOR FOR_LOOP1 AS CUR_NAME CURSOR FOR
DO
---------SQL STATEMENT-------
FOR FOR_LOOP2 AS CUR_NAME1 CURSOR FOR
DO
---------SQL STATEMENT-------
END FOR;
END FOR;
END;
I need to execute NESTED CURSOR or FOR LOOP in Teradata, by taking the output of first cursor value, I need do execute the second cursor.
Can any one guide me, please!
Looks like you worked on Oracle before :-)
Although this is possible in Teradata using exactly the syntax you provided it's not recommended as cursors are sequential by nature while Teradata is a parallel DBMS. Cursors are already evil, but nested cursors are even worse.
Most cursors processing data can be rewritten, e.g. using Windowed Aggregate Functions (best case), have a look at George Coleman's blog
Can you provide the actual code?

difference between cursor and select in a loop

I have been having this question for while now
we can Implement a cursor for Example
SET serveroutput ON;
DECLARE
CURSOR test_cursor
IS
SELECT * FROM employees;
BEGIN
FOR i IN test_cursor
LOOP
DBMS_OUTPUT.PUT_LINE(i.employee_id||' '||i.First_name);
END LOOP;
END;
Also we can implement the same in below way
SET serveroutput ON;
BEGIN
FOR rec IN
(SELECT * FROM employees
)
LOOP
DBMS_OUTPUT.PUT_LINE(rec.employee_id ||' ' ||rec.First_name);
END LOOP;
END;
Why do we need a cursor here then? Please could you let me know the differences and its advantages/disadvantages?
In both cases, you actually use cursors.
The first one is declared and named (explicit).
The second one is anonymous (implicit).
http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/01_oview.htm#740.
I usually use explicit cursors for better code readability and in cases, when I want to reuse the cursor, I can fetch the data from result cache or fetch the data into variable and iterate through an array.
Also, as far as I know, execution plan is not generated as often as while using the implicit cursor (the DB searches for the query in SGA by query's hash and can find already stored execution plan, thus skips the execution plan generation).
https://docs.oracle.com/database/121/TGSQL/tgsql_sqlproc.htm#TGSQL175
So firstly, these are both known as cursor FOR LOOPs.
http://docs.oracle.com/database/121/LNPLS/cursor_for_loop_statement.htm#LNPLS1143
One usability difference between the two forms is that the second form places the SQL that is executing directly before the code in which the result set is used. This can make it easier to understand the code.
One useful syntax difference is that in the first form you can pass parameters into the cursor to modify its behaviour (see above link for syntax). So if you use the same basic cursor definition multiple times, but with different parameters to pass in, then use the former.

SQLite Function that performs additional queries

I have written a custom SQLite function that transforms a string as it is copied from one table to another. It's very basic and has does its job well for quite a while. The query looks like this:
INSERT INTO Table2 (field1) SELECT MYTRANSFORM(field2) FROM Table2;
Now I need to modify the behavior of that function so that it does a lookup on another table and factors the result into how it transforms the value. Is that possible? Has anyone done it successfully?
This is possible; you can execute other SQL queries from within your function, as long as you do not call your function recursively.

Increase performance on insert cursor?

I would like to ask you how would you increase the performance on Insert cursor in this code?
I need to use dynamic plsql to fetch data but dont know how to improve the INSERT in best way. like Bulk Insert maybe?
Please let me know with code example if possible.
// This is how i use cur_handle:
cur_HANDLE integer;
cur_HANDLE := dbms_sql.open_cursor;
DBMS_SQL.PARSE(cur_HANDLE, W_STMT, DBMS_SQL.NATIVE);
DBMS_SQL.DESCRIBE_COLUMNS2(cur_HANDLE, W_NO_OF_COLS, W_DESC_TAB);
LOOP
-- Fetch a row
IF DBMS_SQL.FETCH_ROWS(cur_HANDLE) > 0 THEN
DBMS_SQL.column_value(cur_HANDLE, 9, cont_ID);
DBMS_SQL.COLUMN_VALUE(cur_HANDLE, 3, proj_NR);
ELSE
EXIT;
END IF;
Insert into w_Contracts values(counter, cont_ID, proj_NR);
counter := counter + 1;
END LOOP;
You should do database actions in sets whenever possible, rather than row-by-row inserts. You don't tell us what CUR_HANDLE is, so I can't really rewrite this, but you should probably do something like:
INSERT INTO w_contracts
SELECT ROWNUM, cont_id, proj_nr
FROM ( ... some table or joined tables or whatever... )
Though if your first value there is a primary key, it would probably be better to assign it from a sequence.
Solution 1) You can populate inside the loop a PL/SQL array and then just after the loop insert the whole array in one step using:
FORALL i in contracts_tab.first .. contracts_tab.last
INSERT INTO w_contracts VALUES contracts_tab(i);
Solution 2) if the v_stmt contains a valid SQL statement you can directly insert data into the table using
EXECUTE IMMEDIATE 'INSERT INTO w_contracts (counter, cont_id, proj_nr)
SELECT rownum, 9, 3 FROM ('||v_stmt||')';
"select statement is assembled from a website, ex if user choose to
include more detailed search then the select statement is changed and
the result looks different in the end. The whole application is a web
site build on dinamic plsql code."
This is a dangerous proposition, because it opens your database to SQL injection. This is the scenario in which Bad People subvert your parameters to expand the data they can retrieve or to escalate privileges. At the very least you need to be using DBMS_ASSERT to validate user input. Find out more.
Of course, if you are allowing users to pass whole SQL strings (you haven't provided any information regarding the construction of W_STMT) then all bets are off. DBMS_ASSERT won't help you there.
Anyway, as you have failed to give the additional information we actually need, please let me spell it out for you:
will the SELECT statement always have the same column names from the same table name, or can the user change those two?
will you always be interested in the third and ninth columns?
how is the W_STMT string assembled? How much control do you have over its projection?

Resources