PLSQL - Parameter cursor with different return - oracle

I know the title is saying nothing... but the argument is a little "complex" to explain in a single row.
All the code i'm writing is just an example, my current code is from other table etc, but the behaviour is the same.
i have defined a cursor like this:
CURSOR emp_cur (l_type)
IS
with emp_general AS (select *
from emp
where type = l_type),
emp_active AS (select *
from emp_geral
where status = ACTIVE_STATUS),
emp_inactive AS (select *
from emp_general
where status = INACTIVE_STATUS)
select distinct name, department
from emp_active
minus
select distinct name, department
from emp_inactive;
This cursor take a parameter for filter emp type and make a minus to fetch ACTIVE - INACTIVE emp.
This cursor return name and department.
Now have to declare different cursor with different "select" statemant, for example:
select location
from emp_active
select location
from emp_active
I would like to dont duplicate my cursor just to change the select. There is a way to do this and avoid code duplication (withuout using DynamicSQL - Difficult to debug in production enviroment)?

You could create two Global temporary tables explicitly once(not on the fly):
emp_active_gtt
emp_inactive_gtt
Such that, each temp table will have the entire result set of active and inactive records respectively.
For example, in the code you would do:
insert into emp_active_gtt
select *
from ....
where status ='ACTIVE'
Similarly, for inactive records:
insert into emp_inactive_gtt
select *
from ....
where status ='INACTIVE'
You could now use the two tables in the scope of the session anywhere to get the required rows.
Read more about GTT in the documentation here https://docs.oracle.com/database/121/SQLRF/statements_7002.htm#i2153132

Related

How to delete multiple rows using shuttle page item in Oracle Apex?

My requirement is that users must be able to select from a shuttle page item the employee numbers that they need to delete from a table. In the back end I have a plsql code that is supposed to delete the selected employee numbers as follows:
BEGIN
delete from employees where empno in (:P7_EMPLOYEE_NUMBER);
END;
Additionally I will have more logic in the code to do other stuff, however I am not able to delete multiple rows, if I select 1 employee number in the shuttle item, I am able to delete the record successfully, when I try to delete more than one record I keep getting the following error:
Ajax call returned server error ORA-01722: invalid number for Execute Server-Side Code
I changed the code to:
BEGIN
delete from employees where empno in (to_number(:P7_EMPLOYEE_NUMBER));
END;
and I keep getting the same error message.
How can I make this work?
The API APEX_STRING has a number of utility functions to deal with multi-value page items (select lists, checkbox, shuttles). To convert a colon separated list to an array, use APEX_STRING.SPLIT.
DELETE
FROM
employees
WHERE empno IN
(SELECT column_value
FROM table(apex_string.split(: P7_EMPLOYEE_NUMBER,':'))
);
A shuttle item contains colon-separated values, which means that you have to split it to rows, e.g.
delete from employees
where empno in (select regexp_substr(:P7_EMPLOYEE_NUMBER, '[^:]+', 1, level)
from dual
connect by level <= regexp_count(:P7_EMPLOYEE_NUMBER, ':') + 1
);
The APEX engine will always submit multi-values items as a single colon-delimited string, for example: 1:2:3:4
You need to split the string into multiple values so that you can process them.
There are multiple ways to do this:
Using an the APEX_STRING.SPLIT or the APEX_STRING.SPLIT_NUMBERS API in a subquery
delete from employees
where empno in (select column_value
from apex_string.split_numbers(:P7_EMPLOYEE_NUMBER, ':'));
Using the APEX_STRING API with the MEMBER OF function
delete from employees
where empno member of apex_string.split_numbers(:P7_EMPLOYEE_NUMBER, ':');
Note that the member of needs to have the same type. In this case empno is a number so you must use the split_numbers API.
Using a regular expression to split the values
delete from employees
where empno in (select regexp_substr(:P7_EMPLOYEE_NUMBER, '[^:]+', 1, level)
from dual
connect by level <= regexp_count(:P7_EMPLOYEE_NUMBER, ':') + 1
);
I prefer using option 2 as it's less code and easier to read.

How can I pass a PL/SQL cursor record created from multiple tables?

This is PL/SQL in a 12c database.
I need to be able to pass a cursor record to a function. The problem is that the cursor is from three different tables and one of them must use a * to select all of the (hundreds) of fields in that table.
It works if I select distinct fields (from a smaller test table) and it works if I use a select * from one table and no other fields (no other tables involved), but I can't find any way to make this work when selecting from three tables (examples only show two) and using a * (to select all fields) from one of the tables.
I've tried FETCH INTO and SELECT INTO with a pre-defined cursor. I've tried using a cursor record with a FOR myRecord IN (SELECT a.*, ...) and
creating a matching object (since records can't be created at the schema level)
These work
myVarA a%ROWTYPE;
SELECT a.* INTO myVarA
FROM a;
SELECT a.myAfield, b.myBfield INTO myVarA, myVarB
FROM a, b;
But I need this to work:
myVarA a%ROWTYPE;
SELECT a.*, b.myBfield INTO myVarA, myVarB
FROM a, b;
Using a cursor record
myRecord myObjectTypeWithAllFields; -- ojbect, not record as record can't be declared at schema level
FOR myRecord IN (SELECT a.*, b.myBfield FROM a, b);
newVar := myFunction(myRecord); -- this won't work
fails on the function call with PLS-00306: wrong number or types of arguments in call to myFunction;
The function will do a lot of grunt work that is similar in many packages, but there is also a large amount of unique work
in each package, so I can't just process the entire cursor loop in the function. I really need to pass one row at a time to the function.
Is there a way to do this?
You can define a cursor in a package - whether or not you will actually use it - with the same select list:
create package p as
cursor c is select a.*, b.myBField
from a, b; -- but use proper join syntax
end;
/
Then define your function argument using that cursor's %rowtype:
create function myFunction(p_record p.c%rowtype) return ... as ...
Then your block will work:
FOR myRecord IN (SELECT a.*, b.myBfield FROM a, b) LOOP
newVar := myFunction(myRecord);
END LOOP;
db<>fiddle demo
The cursor for loop could then use the cursor defined in the package if you wanted it to.
Incidentally, in your object version, the variable declaration:
myRecord myObjectTypeWithAllFields;
is redundant; the myRecord in FOR myRecord... is completely independent. So it doesn't even attempt to use the object type.
You are using a %rowtype anchor so I am assuming an exact fetch. Oracle does not allow to use of multiple records with "into" clauses. But we can have a workaround on that.
DECLARE
emprec EMPLOYEES%ROWTYPE;
deptname DEPARTMENTS.department_name%type;
BEGIN
select a.* into emprec
from EMPLOYEES a
WHERE EMPLOYEE_ID = 100;
SELECT DEPARTMENT_NAME into deptname
from DEPARTMENTS where DEPARTMENT_ID = emprec.DEPARTMENT_ID;
END;
This example shows how you can fetch your a.* in a record and have inner join with another table and have b.myBfield into another record.
And once again these are records so I am assuming it is an exact fetch.
If it is not what you want let me know in the comment.

Oracle puzzle: Selecting from a non-existing table

I have a table named "libisatz" in my database, and there is no table, nor view with name "libiSatz" (with capital S instead of s) and I don't find any kind of object in my schema having name "libiSatz". But, surprisingly selecting from "libiSatz" results in the same result as if I had written "libisatz". If I change any other letter in this name from lower case to upper case (e.g. I write "Libisatz", then I get an error. How can this be?.
ADDENDUM
I've checked the ideas of #Jon Heller with the following result:
Both select * from DBA_OBJECTS where OBJECT_NAME like 'libi_atz'; and select * from DBA_OBJECTS where lower(OBJECT_NAME) = 'libisatz'; returns one single row (it is the "libisatz" table)
select * from DBA_OBJECTS where OBJECT_NAME = 'libisatz'; returns one row and select * from DBA_OBJECTS where OBJECT_NAME = 'libiSatz'; returns no row.
Both select * from DBA_SQL_TRANSLATIONS; and select * from DBMS_ADVANCED_REWRITE; results in ORA-00942: table or view does not exist
select * from DBA_REWRITE_EQUIVALENCES; results in no rows selected
select DUMP(OBJECT_NAME) from DBA_OBJECTS where lower(OBJECT_NAME) = 'libisatz'; returns Typ=1 Len=8: 108,105,98,105,115,97,116,122
So it seems that the puzzle is not yet solved.
ADDENDUM 2.
When I try to create a view named "libiSatz" then I get
ORA-00955: name is already used by an existing object
in spite of the results above.
After I renamed "libiSatz" to "oraclepuzzle",
select count(*) from "libisatz"; and "select count(*) from "oraclepuzzle"; works, but select count(*) from "libiSatz"; doesn't.
select * from dba_objects where object_name in ( 'oraclepuzzle', 'libisatz', 'libiSatz'); returns one row with object_name "oraclepuzzle".
Do you have SQL translations, rewrite equivalances, or UTF8 characters?
The SQL translation framework was built to allow applications designed for other database types to seamlessly query Oracle. But instead of translating syntaxes, the feature could also be used to silently change your queries. For example, here is an example of querying a table that does not exist in order to workaround table size limitations. Check the view DBA_SQL_TRANSLATIONS.
Rewrite equivalences can be created by the package DBMS_ADVANCED_REWRITE, and can be used to silently change the results of wrong queries or for some rare performance problems. (In my simple tests I wasn't able to get this query to work for invalid queries, but I bet there is a way to make it work.) Check the view DBA_REWRITE_EQUIVALENCES.
UTF8 characters may be silently swapped out for similar ASCII characters. This probably depends on your database and client character set settings. The below example is pretty obviously not an ASCII "S", but you may have a more subtle problem. Check the source of your values, retype them manually, and use the DUMP function to evaluate the binary of the characters.
SQL> create table "libisatz"(a number);
Table created.
SQL> -- An uppercase "S" does not work
SQL> select * from "libiSatz";
select * from "libiSatz"
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> -- But a "LATIN SMALL LETTER S WITH CARON" works.
SQL> select * from "libiĆĄatz";
no rows selected
Lastly, are you 100% sure that the object doesn't exist on your database? The above examples are possible, but extremely rare. Triple-check DBA_OBJECTS.OBJECT_NAME for the mystery object.
My deafult Oracle object names are case insensitive.
So, when you issue teh command:
CREATE TABLE the_table ..
CREATE TABLE The_Table ..
CREATE TABLE THE_TABLE ..
The underlying object name in all cases is THE_TABLE, but you can access it using any mix of upper/lower case:
SELECT * FROM THE_TABLE
SELECT * FROM tHe_TaBlE
SELECT * FROM the_table
Will all work.
When a table is created with the name wrapped in double-quotes, the name becomes case-sensitive.
So, if you issue:
CREATE TABLE "libiSatz" ..
Then the table name in all SQL statements must match the exact name in the double quotes, i.e.
SELECT * FROM "libiSatz" is OK (Correction following comments)
SELECT * FROM libisatz is NOT OK
SELECT * FROM LibiSatz is NOT OK
When you search for this in USER_OBJECTS or USER_TABLES you will have to match the creation name:
SELECT * FROM USER_OBJECTS WHERE OBJECT_NAME = 'libiSatz';

Declaring and using variables in PL-SQL

I am new to PL-SQL. I do not understand why I am getting the error "PLS-00428: an INTO clause is expected in this SELECT statement"
What I'm trying to accomplish is to create a variable c_limit and load it's value. I then want to use that variable later to filter data.
Basically I am playing around in the demo db to see what I can/can't do with PL-SQL.
The code worked up to the point that I added "select * from demo_orders where CUSTOMER_ID = custID;"
declare
c_limit NUMBER(9,2);
custID INT;
BEGIN
custID := 6;
-- Save the credit limit
select credit_limit INTO c_limit
from demo_customers cust
where customer_id = custID;
select * from demo_orders where CUSTOMER_ID = custID;
dbms_output.Put_line(c_limit);
END;
If you are using a SQL SELECT statement within an anonymous block (in PL/SQL - between the BEGIN and the END keywords) you must select INTO something so that PL/SQL can utilize a variable to hold your result from the query. It is important to note here that if you are selecting multiple columns, (which you are by "SELECT *"), you must specify multiple variables or a record to insert the results of your query into.
for example:
SELECT 1
INTO v_dummy
FROM dual;
SELECT 1, 2
INTO v_dummy, v_dummy2
FROM dual;
It is also worth pointing out that if your SELECT * FROM.... will return multiple rows, PL/SQL will throw an error. You should only expect to retrieve 1 row of data from a SELECT INTO.
Looks like the error is from the second select query.
select * from demo_orders where CUSTOMER_ID = custID;
PL-SQL won't allow a standalone sql select query for info.
http://pls-00428.ora-code.com/
You need to do some operation with the second select query

PL/SQL procedure - too many values

I'm sure this is something simple, but I'm really new to PL/SQL and this has me stuck.
I've written a simple stored procedure to return a few values about a customer. Right off the bat, the %rowtype's are not coming up as reserved keywords but the compiler isn't flagging those as errors.
It is, however, ignoring the entire SQL statement flagging the line FROM demo_customers as too many values. Even if I try reducing it to only select one column it still gives me the same error.
create or replace
PROCEDURE GETCUSTOMER
(
arg_customerID demo_customers.customer_id%type,
returnRec OUT demo_customers%rowtype
)
AS
BEGIN
SELECT customer_id, cust_first_name, cust_last_name, cust_email
INTO returnRec
FROM demo_customers
WHERE customer_id = arg_customerID ;
END GETCUSTOMER;
If you want to select into a %ROWTYPE record, you'll want to do a SELECT * rather than selecting individual columns
create or replace
PROCEDURE GETCUSTOMER
(
arg_customerID demo_customers.customer_id%type,
returnRec OUT demo_customers%rowtype
)
AS
BEGIN
SELECT *
INTO returnRec
FROM demo_customers
WHERE customer_id = arg_customerID ;
END GETCUSTOMER;
If you select 4 columns explicitly, Oracle expects you to have 4 variables to select those values into.

Resources