How to change below procedure to (update & insert) instead of (delete &insert) in Oracle - oracle

I want to update the record if already exists based on where condition or else insert. I have written query with delete and insert I am facing difficulty into converting into update and insert.
PS: I have tried using SQL%ROWCOUNT but I think i missed somewhere in syntax.
Any help would be appreciated.
Below is the proc i am using
Create Or Replace Procedure sal_proc(Empid Varchar2,Fmdt Date,bp Number)
As
Begin
--delete
delete from Emp_Sal
Where Empid = Empid
And Fmdt = Fmdt;
--insert
Insert Into Emp_Sal(empid,fmdt,Basicpay) Values (empid,fmdt,Bp);
End;

You do not need a procedure; you can use MERGE to update or insert a row at the same time:
merge into Emp_Sal e
using (
/* your values to insert/update */
select 2 as Empid, 'c' as Fmdt, 100 as Bp from dual
) x
on ( e.Empid = x.Empid And e.Fmdt = x.Fmdt)
when matched
then /* if a record exists, update */
update set Basicpay = Bp
when not matched
then /* it the record does not exist, insert */
insert values (x.empid, x.fmdt, x.Bp)
Of course you can use this inside a procedure to handle your input parameters or do whatever you may need to do in your procedure:
Create Or Replace Procedure sal_proc(Empid Varchar2,Fmdt Date,bp Number)
As
Begin
merge into Emp_Sal e
using (
/* your values to insert/update */
select Empid as Empid, Fmdt as Fmdt, bp as Bp from dual
) x
on ( e.Empid = x.Empid And e.Fmdt = x.Fmdt)
when matched
then /* if a record exists, update */
update set Basicpay = Bp
when not matched
then /* it the record does not exist, insert */
insert (empid,fmdt,Basicpay) values (x.empid, x.fmdt, x.Bp);
End;
An hint: use parameter names different fron column names to avoid confusion; a good practice could be use parameter names like p_XXX; just an example of how dangerous this can be:
SQL> create or replace procedure checkPar(n in number) is
2 c number;
3 begin
4 select count(1)
5 into c
6 from checkTab
7 where n = n;
8 --
9 dbms_output.put_line(c);
10 end;
11 /
Procedure created.
SQL> select * from checkTab;
N
----------
1
2
3
SQL> exec checkPar(1);
3
PL/SQL procedure successfully completed.
SQL> exec checkPar(999);
3
PL/SQL procedure successfully completed.

Not very efficient way but should work if huge data is not present in tables
CREATE OR REPLACE PROCEDURE sal_proc (E_Empid VARCHAR2, F_Fmdt DATE, b_bp NUMBER)
AS
var number;
BEGIN
Begin
--Checking if record exists
select 1
into var
from Emp_Sal
Where Empid = E_Empid
And Fmdt = F_Fmdt;
exception
when no_data_found then
var:= 0;
End;
if var <> 1 then
--insert
INSERT INTO Emp_Sal (empid, fmdt, Basicpay)
VALUES (e_empid, f_fmdt, b_Bp);
else
update Emp_Sal
set col ....<>;
end if;
END;

Related

How to prevent Oracle from calling a function for every attribute of the function result

I've created a package, containing a function that returns an object.
When retrieving the object details through sql, the function is called multiple times - once for every detail retrieved.
I believe it should be possible for it to just be called once instead.
Following is an example that demonstrates the issue:
CREATE OR REPLACE TYPE t_test AS OBJECT (
v1 VARCHAR2(10),
v2 VARCHAR2(10),
v3 VARCHAR2(10),
times_called NUMBER
);
/
CREATE OR REPLACE PACKAGE test_pkg AS
times_called NUMBER :=0;
FUNCTION test(something IN VARCHAR2) RETURN t_test;
PROCEDURE reset;
END test_pkg;
/
CREATE OR REPLACE PACKAGE BODY test_pkg IS
PROCEDURE reset IS
BEGIN
times_called := 0;
END;
FUNCTION test(something IN VARCHAR2) RETURN t_test IS
BEGIN
times_called := times_called + 1;
RETURN t_test('first', 'second', 'third', times_called);
END;
END test_pkg;
/
Here we can see that the function is invoked four times:
SQL> SELECT t.r.v1, t.r.v2, t.r.v3, t.r.times_called FROM (
2 SELECT test_pkg.test('x') r FROM DUAL
3 ) t;
R.V1 R.V2 R.V3 R.TIMES_CALLED
---------- ---------- ---------- --------------
first second third 4
SQL>
If we reset the counter, and only select two attributes, we can see it's called twice:
SQL> exec test_pkg.reset();
PL/SQL procedure successfully completed.
SQL> SELECT t.r.v1, t.r.times_called FROM (
2 SELECT test_pkg.test('x') r FROM DUAL
3 ) t;
R.V1 R.TIMES_CALLED
---------- --------------
first 2
SQL>
The actual stored procedure is more expensive, so I'd like to avoid re-calling it for every attribute listed.
The solution has to work on Oracle 10gr2
Oracle is not materializing the sub-query and is pushing the function calls to the outer query. You need to force the SQL engine to materialize the inner query either by:
Using a seemingly unnecessary ROWNUM > 0 filter:
SELECT t.r.v1, t.r.v2, t.r.v3, t.r.times_called
FROM (
SELECT test_pkg.test('x') r
FROM DUAL
WHERE ROWNUM > 0
) t;
or, you should be able to use the (undocumented) /*+ materialize */ hint but, for an unknown reason, it doesn't seem to want to materialize this particular query (although it does work for similar problems).
You can also (as pointed out in comments by William Robertson) use the /*+ NO_MERGE */ hint which "causes Oracle not to merge mergeable views":
SELECT t.r.v1, t.r.v2, t.r.v3, t.r.times_called
FROM (
SELECT /*+ no_merge */
test_pkg.test('x') r
FROM DUAL
) t;
db<>fiddle here

Variables in PLSQL

I want to get the value defined in my Procedure as mentioned below.
declare
city varchar2(50) := 'XYZ';
TYPE table_type is table of table_name%rowtype;
var table_type;
begin
select * bulk collect into var from table_name;
DBMS_OUTPUT.PUT_LINE(var(1).field); -- Output is City
I want the output of
DBMS_OUTPUT.PUT_LINE(var(1).field); -- Output is XYZ
How can I achieve this?
First of all, your code does not work. Second, if you are going to recover a variable, you don't need bulk collect
Example
create table mytest ( c1 varchar2(50) ;
insert into mytest values ( 'XYZ' );
commit;
Then
SQL> set serveroutput on
declare
vcity mytest.c1%type := 'XYZ';
var mytest.c1%type;
begin
select c1 into var from mytest where c1=vcity;
DBMS_OUTPUT.PUT_LINE('vcity is '||vcity||' ');
DBMS_OUTPUT.PUT_LINE('var is '||var||' ');
end;
/SQL> 2 3 4 5 6 7 8 9
vcity is XYZ
var is XYZ
PL/SQL procedure successfully completed.
SQL>
vcity is just a variable defined with the type of the column c1, but
assigned to a constant, in this case 'XYZ'
var is the variable which I use to recover the value of c1 in the
table, whatever that value is.
You don't need bulk collect here at all.
Assuming you have several cities to list, you need to define a collection to house them once selected, then a variable of that collection. So for example:
--setup
create table table_name ( id integer
, city varchar2(10)
);
insert into table_name(id, city)
select level, 'City #' || trunc(dbms_random.value( 10, 75 ))
from dual connect by level <= 10;
-- process
declare
type city_list is table of table_name%rowtype;
var city_list;
begin
select *
bulk collect
into var
from table_name;
for r in 1 .. var.count
loop
dbms_output.put_line(var(r).city); -- Output is City
end loop;
end;
Let's keep remain mystery about why you want like this,
If I understood you , to achieve what you want you have to specify columns instead of '*' and replace the variable city with column field.
Dbfiddle link for your reference (unable to provide via link through mobile device)
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=20f1a1fff11d4acda7acc701ad120d32
DECLARE
city varchar2(50) := 'XYZ';
TYPE table1_type is table of table1%rowtype;
var table1_type;
BEGIN
select city,field2,field3,field4
bulk collect into var
from table1;
DBMS_OUTPUT.PUT_LINE(var(1).field);
END;
/

how to look up another field in Oracle Function

Table 1
ID
----------
1
2
3
4
5
Table 2
ID Desc
------------------------------
A1 Apple
A2 Pear
A3 Orange
I am trying to create a Function in Oracle, so that it add the prefix 'A' in Table 1, and after that I want to look up in Table 2 to get the DESC returned. It has to be a function.
Thank you!!!
You may use the following for creation of such a function :
Create or Replace Function Get_Fruit( i_id table2.description%type )
Return table2.description%type Is
o_desc table2.description%type;
Begin
for c in ( select description from table2 where id = 'A'||to_char(i_id) )
loop
o_desc := c.description;
end loop;
return o_desc;
End;
where
no need to include exception handling, because of using cursor
instead of select into clause.
using table_name.col_name%type for declaration of data types for
arguments or variables makes the related data type of the columns
dynamic. i.e. those would be able to depend on the data type of the
related columns.
the reserved keywords such as desc can not be used as column names
of tables, unless they're expressed in double quotes ("desc")
To call that function, the following might be preferred :
SQL> set serveroutput on
SQL> declare
2 i_id pls_integer := 1;
3 o_fruit varchar2(55);
4 begin
5 o_fruit := get_fruit( i_id );
6 dbms_output.put_line( o_fruit );
7 end;
8 /
Apple
PL/SQL procedure successfully completed
I am not sure with your question- Are you trying to achieve something like this:-
CREATE OR REPLACE FUNCTION Replace_Value
(
input_ID IN VARCHAR2
) RETURN VARCHAR2
AS
v_ID varchar(2);
BEGIN
begin
SELECT distinct a.ID into v_id from Table 2 a where a.ID in (select 'A'||b.id from table1 b where b.id=input_ID);
exception
when others then
dbms_output.put_line(sqlcode);
end;
RETURN v_id;
END Replace_Value;
Are you trying for something like this?
CREATE OR replace FUNCTION replace_value (table_name IN VARCHAR2,
input_id IN INTEGER)
RETURN VARCHAR2
AS
v_desc VARCHAR(20);
BEGIN
SELECT descr
INTO v_desc
FROM table2
WHERE id = 'A' || input_id
AND ROWNUM = 1; -- only needed if there are multiple rows for each id.
RETURN v_desc;
END replace_value;
You may also add an exception handling for NO_DATA_FOUND or INVALID_NUMBER

Checking the date before inserting in a table ORACLE 10g

I have table:
BOOK_DT1 BOOK_DT2 USERNAME
--------- --------- --------------------
22-SEP-17 12-OCT-17 rSK
08-FEB-16 18-FEB-16 chak
05-JAN-17 12-JAN-17 rah
31-JAN-16 01-JUL-16 ABC
While inserting another column, it should check the given dates for BOOK_DT1 and BOOK_DT2 should not come into the dates present in the table.
For EX: insert into table_name('28-SEP-17','12-NOV-17','XYX'); should throw an error, because '28-SEP-17' comes in between 22-SEP-17 and 12-OCT-17.
you can achive this using the after insert trigger. Somting like this:
create or replace trigger date_check_trg
after insert
on your_table_name
v_cnt NUMBER;
begin
select count(*)
into v_cnt
from you_table_name t1
join you_table_name t2
on ( t1.BOOK_DT1 between t2.BOOK_DT1 and t2.BOOK_DT1
or t1.BOOK_DT2 between t2.BOOK_DT1 and t2.BOOK_DT1
)
AND t1.rowid != t2.rowid
;
if v_cnt > 0 then
raise_application_error(-20999, 'intersection error');
end if;
end;
/
If you want to check before the insert then BEFORE INSERT should be what you're looking for. If the name doesn't matter and your new values should not be between any values previously inserted in the table then this is how I would write it:
create or replace trigger trg_date_chk
before insert
on your_table_name for each row
declare
lnCnt NUMBER;
begin
select count(*)
into lnCnt
from you_table_name a
where :new.BOOK_DT1 < a.BOOK_DT1
and :new.BOOK_DT2 > a.BOOK_DT2;
if lnCnt > 0 then
raise_application_error(-20999, 'INSERT ERROR HERE');
end if;
end;
/

ORA-04091 mutating table error when calling a function from a procedure

I have a task:
Write a procedure to update salary (salary * % of increment) in emp table based on grade. Use function to get increment
This is my procedure:
CREATE OR REPLACE
PROCEDURE sal_incre
IS
CURSOR c_cur
IS
SELECT * FROM emp_task;
BEGIN
UPDATE emp_task SET sal = sal + sal_incr(grade_id);
FOR rec IN c_cur
LOOP
dbms_output.put_line(rec.empno||','||rec.ename||','||rec.sal);
END LOOP;
END;
This is my function code:
CREATE OR REPLACE
FUNCTION sal_incr(
p_grade NUMBER)
RETURN
IS
v_inc NUMBER;
BEGIN
SELECT raise_percent
INTO v_inc
FROM sal_inc
WHERE grade_id IN
(SELECT grade_id FROM emp_task WHERE grade_id = p_grade
);
RETURN v_inc;
COMMIT;
END;
When I call the procedure I'm getting:
ORA-04091: table SCOTT.EMP_TASK is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.SAL_INCR", line 8
ORA-06512: at "SCOTT.SAL_INCRE", line 6
ORA-06512: at line 2
What am I doing wrong?
Your function is referring to the same table you're using in the procedure at the point you call that function, which is what causes this error. You're updating and querying it at the same time, in a way that could cause indeterminate (or confusing) results, even though you aren't querying the column you're updating. Oracle is protecting you from yourself here.
In your function you're doing:
SELECT raise_percent
INTO v_inc
FROM sal_inc
WHERE grade_id IN
(SELECT grade_id FROM emp_task WHERE grade_id = p_grade
);
There is no need to look at the emp_task table here. Unless you've been passed an nonexistent value (which can't happen from your procedure) the subquery can only return the original p_grade argument value, so this is the same as:
SELECT raise_percent
INTO v_inc
FROM sal_inc
WHERE grade_id = p_grade;
If you do that the function no longer refers to emp_task, so it won't throw the mutating trigger/function error when it's called as part of an update.
And your function should not be issuing a COMMIT - let the calling procedure, or preferably the session that calls the procedure, decide whether the who transaction should be committed or rolled back.
Also, from the title and column name it looks like raise_percent is a percentage, so you need to use that to find the value to multiply by - you shouldn't add that percentage figure. If that gives you a value of 2 for a 2% raise, for example, you need to either do this in your procedure:
UPDATE emp_task SET sal = sal * (1 + (sal_incr(grade_id)/100));
Or more neatly have your function return 1 + (raise_percent/100) and do:
UPDATE emp_task SET sal = sal * sal_incr(grade_id);
Change the procedure like this:
create or replace
procedure sal_incre
is
cursor c_cur is
select distinct e.grade_id,e.ename,e.sal from sal_inc s
join emp_task e on e.grade_id = s.grade_id order by e.ename ;
v_incr number;
begin
for f_cur in c_cur
loop
v_incr := sal_incr(f_cur.grade_id);
update emp_task set sal = sal + v_incr;
dbms_output.put_line('Emp Name : '||f_cur.ename||','
||' Sal:'||f_cur.sal||','||' Grade: '||f_cur.grade_id);
end loop;
end;

Resources