Oracle Insert Into If NOT Exist - sql

I'm wirting and Pl_SQL Script to do some inserts if an condition not Exist
and its not working for me :(
this is my code
paramS in an CURSOR
FOR ps IN paramS LOOP
compteur := 5;
LOOP
IF NOT EXISTS
(SELECT *
FROM carp.Table1
WHERE FK_tab1 =ps.id_tab1
AND DIC_TYPE = compteur
)
BEGIN
INSERT
INTO carp.Table1
(
id,
FK_tab1,
DIC_TYPE
)
VALUES
(
id.nextval ,
ps.id_tab1 ,
compteur
)
END
compteur:=compteur-1;
commit;
EXIT WHEN compteur <0;
END LOOP;
END LOOP;
thanks in advance

Usually I use such checking , If not exists doesnt work on oracle (as far as I know)
DECLARE
CNT NUMBER(4);
BEGIN
SELECT COUNT(1) INTO CNT
FROM carp.Table1
WHERE FK_tab1 =ps.id_tab1
AND DIC_TYPE = compteur
IF CNT = 0 THEN
INSERT
INTO carp.Table1
(
id,
FK_tab1,
DIC_TYPE
)
VALUES
(
id.nextval ,
ps.id_tab1 ,
compteur
)
End IF;
END;
/
commit
/

You can use NO_DATA_FOUND exception
BEGIN
SELECT * FROM carp.Table1
WHERE FK_tab1 = ps.id_tab1
AND DIC_TYPE = compteur
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO carp.Table1 (id, FK_tab1, DIC_TYPE)
VALUES(id.nextval, ps.id_tab1, compteur);
COMMIT;
END

You can avoid count() using:
DECLARE FG_EXISTS NUMBER(1);
BEGIN
SELECT CASE WHEN EXISTS(SELECT 1
FROM CARP.TABLE1
WHERE FK_TAB1 =PS.ID_TAB1
AND DIC_TYPE = COMPTEUR
) THEN 1 ELSE 0 END INTO FG_EXISTS
FROM DUAL;
IF FG_EXISTS = 0 THEN INSERT ...

Related

HOW TO DEAL WITH THESE ERROR ,PL/SQL Compilation unit analysis terminated & PSL-00201 : 'TABLE NAME' MUST BE DECLARED

I am creating a function in Oracle but it's not getting compiled and I am getting two errors
Error 1.
Error: PL/SQL: Compilation unit analysis terminated
Error 2.
Error(2,16): PLS-00201: identifier 'DIV_DUR_PRICE_TABLE' must be
declared
HERE IS THE CODE
CREATE OR REPLACE FUNCTION DIV_DAR(FID IN VARCHAR, DATE1 IN DATE, DATE2 IN DATE)
RETURN DIV_DUR_PRICE_TABLE PARALLEL_ENABLE AS
PRAGMA AUTONOMOUS_TRANSACTION;
CNT NUMBER;
V_RET DIV_DUR_PRICE_TABLE;
BEGIN;
EXECUTE IMMEDIATE 'DELETE from GTT_DIV_DUR_PRICE_TABLE';
Insert Into GTT_DIV_DUR_PRICE_TABLE
(select mydate, column1, column2, 0 as Final_value from tablename)
-- please refer my previous question to understand the code written ahead
declare
v_num integer := 1;
v_column1 number(8,2);
v_column2 number(8,2);
v_Final_value number(8,2);
begin
for rec in (select * from GTT_DIV_DUR_PRICE_TABLE order by mydate)
loop
if(v_num = 1) then
update tab set Final_value = column1 where mydate = rec.mydate;
else
if(rec.column2 is not null) then
update tab set Final_value =
v_Final_value * (v_column1/rec.column1) +
rec.column2 * (v_column1/v_Final_value) where mydate = rec.mydate;
else
update tab set Final_value =
v_Final_value * (rec.column1 / v_column1) where mydate = rec.mydate;
end if;
end if;
v_num:= v_num +1;
v_column1 := rec.column1;
v_column2 := rec.column2;
select final_value into v_Final_value from GTT_DIV_DUR_PRICE_TABLE
where mydate = rec.mydate;
end loop;
end;
SELECT
CAST(
MULTISET(
SELECT * FROM GTT_DIV_DUR_PRICE_TABLE order by P_DATE desc
)AS DIV_DUR_PRICE_TABLE
) INTO V_RET FROM DUAL;
COMMIT;
RETURN V_RET;
END DIV_DAR;

Converting Merge clause with Bulk collect/FORALL in pl/sql

I wrote a procedure where the data gets updated/inserted simultaneously to the destination table from source table. The procedure is working fine for less no of records, but when i try to execute more records its taking more time to perform the operation.
Can we convert merge clause with bulk collect where the logic remains same ? i dint find any useful resources.
I have attached my merge procedure .
create or replace PROCEDURE TEST1 (
p_array_size IN NUMBER
) IS
CURSOR dtls IS SELECT DISTINCT
account_num
FROM
table1
WHERE
rprtd_till_dt = (
SELECT
dt - 1
FROM
dates
WHERE
id = 'odc'
);
TYPE data_tbl IS TABLE OF dtls%rowtype;
data data_tbl;
BEGIN
DECLARE
v_noofDays NUMBER:=0;
currentDt DATE;
BEGIN
SELECT dt INTO currentDt FROM dates WHERE id = 'odc';
BEGIN
OPEN dtls;
LOOP
FETCH dtls BULK COLLECT INTO data LIMIT p_array_size;
EXIT WHEN data.COUNT = 0;
FOR i IN 1..data.COUNT
LOOP
IF(TRUNC(data(i).creation_dt,'MM') = TRUNC(currentDt,'MM')) THEN
v_noofDays := currentDt - 1 - data(i).creation_dt;
ELSE
v_noofDays := currentDt - TRUNC(currentDt,'MM');
END IF;
MERGE INTO table1 updtbl USING ( SELECT
d.*
FROM
table2 d,
(
SELECT
b.prdct_id,
FROM
table3 a,
table2 b
WHERE
a.ir_id = b.ir_id
AND a.price_component_id = b.price_component_id
AND a.financial_institution_id = b.financial_institution_id
GROUP BY
b.prdct_id,
) e
WHERE
d.prdct_id = e.prdct_id
AND d.bndng_typ = data(i).bndng_typ
AND d.bndng_val = data(i).bndng_val
AND d.financial_institution_id = data(i).financial_institution_id
AND d.prdct_id = data(i).prdct_id
AND d.prdct_sub_id = data(i).prdct_sub_id
AND d.instrmnt_id = data(i).instrmnt_id
)
inp ON (
updtbl.POS_NUM = data(i).POS_NUM
AND updtbl.POS_TYPE = data(i).POS_TYPE
AND updtbl.PRICE_COMPONENT_ID = inp.PRICE_COMPONENT_ID
AND updtbl.RPRTD_TILL_DT = data(i).RPRTD_TILL_DT
)
WHEN NOT MATCHED THEN
INSERT VALUES (
data(i).loan_account_num,
inp.ir_id,
inp.price_component_id,
)
WHEN MATCHED THEN
update SET SEQ_NUM=1,
NET_INTRST_AMT=round(data(i).curr_loan_bal*inp.price_component_value*v_noofDays/36000,2),
DM_BTID=200
WHERE SEQ_NUM=2;
COMMIT;
END LOOP;
END LOOP;
CLOSE dtls;
END;
END;
END TEST1;
/
If anyone can help me to guide the syntax on how to achieve the above procedure using bulk collect will be helpful.
I know its a bit late, but use the following for future if you haven't solved it yet
drop table projects;
create table projects (
proj_id integer not null primary key,
proj_title varchar2(20)
);
insert into projects (proj_id, proj_title) values (1, 'Project One');
insert into projects (proj_id, proj_title) values (2, 'Project Two');
commit;
select *
from projects;
declare
type varray_t is varray(2) of projects%rowtype;
arr varray_t;
begin
with test_data as (select 2 as proj_id, 'New Project Two' as proj_title from dual
union all select 3 as proj_id, 'New Project Three' as proj_title from dual)
select proj_id, proj_title
bulk collect into arr
from test_data;
forall i in arr.first .. arr.last
merge into projects
using (select arr(i).proj_id as proj_id,
arr(i).proj_title as proj_title
from dual) mrg
on (projects.proj_id = mrg.proj_id)
when matched then update set projects.proj_title = mrg.proj_title
when not matched then insert (proj_id, proj_title) values (mrg.proj_id, mrg.proj_title);
dbms_output.put_line(sql%rowcount || ' rows merged');
commit;
end;
I hope this will give you kind of idea. Avoid the copy and paste and check the syntax.
create or replace PROCEDURE TEST1 (
p_array_size IN NUMBER
) IS
CURSOR dtls IS SELECT DISTINCT
account_num
FROM
table1
WHERE
rprtd_till_dt = (
SELECT
dt - 1
FROM
dates
WHERE
id = 'odc'
);
TYPE data_tbl IS TABLE OF dtls%rowtype;
data data_tbl;
BEGIN
DECLARE
v_noofDays NUMBER:=0;
currentDt DATE;
BEGIN
SELECT dt INTO currentDt FROM dates WHERE id = 'odc';
BEGIN
OPEN dtls;
LOOP
FETCH dtls BULK COLLECT INTO data LIMIT p_array_size;
EXIT WHEN data.COUNT = 0;
FORALL rec in data.first .. data.last
MERGE INTO table1 updtbl USING (
SELECT
d.* FROM
table2 d,(
SELECT
b.prdct_id
FROM
table3 a,
table2 b
WHERE
a.ir_id = b.ir_id
AND a.price_component_id = b.price_component_id
AND a.financial_institution_id = b.financial_institution_id
GROUP BY
b.prdct_id
) e
WHERE
d.prdct_id = e.prdct_id
AND d.bndng_typ = data(rec).bndng_typ
AND d.bndng_val = data(rec).bndng_val
AND d.financial_institution_id = data(rec).financial_institution_id
AND d.prdct_id = data(rec).prdct_id
AND d.prdct_sub_id = data(rec).prdct_sub_id
AND d.instrmnt_id = data(rec).instrmnt_id
)
inp ON (
updtbl.POS_NUM = data(rec).POS_NUM
AND updtbl.POS_TYPE = data(rec).POS_TYPE
AND updtbl.PRICE_COMPONENT_ID = data(rec).PRICE_COMPONENT_ID
AND updtbl.RPRTD_TILL_DT = data(rec).RPRTD_TILL_DT
)
WHEN NOT MATCHED THEN
INSERT VALUES (
data(rec)
)
WHEN MATCHED THEN
update SET SEQ_NUM=1,
NET_INTRST_AMT=round(data(rec).curr_loan_bal*inp.price_component_value*v_noofDays/36000,2),
DM_BTID=200
WHERE SEQ_NUM=2;
END LOOP;
CLOSE dtls;
END;
END;
END TEST1;
Merge is always better than forall for atomic updates.
A simplistic use case is
https://ograycoding.wordpress.com/2012/10/13/oracle-merge-v-bulk-collect-and-forall/

Error: Table or view does not exist in PL SQL package

I have a package called 'S_PKG' in schema 'A'. I want to migrate it into schema B. What I did was I copied the code and executed in B schema. Then I wanted to execute the following pl sql script in which the 'S_PKG' is used in schema B.
select to_char(sysdate,'YYYYMMDD - HH:MI:SS AM') date_time
from dual
/
insert into zzz_ccc
select zzz_ccc_seq.nextval,to_char(sysdate,'YYYYMMDD - HH:MI:SS AM'),
'Start S Load tab',8,user,(select * from global_name)
from dual
/
commit
/
insert into zzz
select zzz_seq.nextval,to_char(sysdate,'YYYYMMDD - HH:MI:SS AM'),
'Start S Load tab',
(select trim(ruser)||' '||trim(rdbase)
from zzz_ccc where ss = 8
and rr = (select max(rr) from zzz_ccc where ss = 8)),
null,null,null,null,null,null,
(select max(rr) from zzz_ccc where ss = 8)
from dual
/
commit
/
DECLARE
PV_PRD_ID VARCHAR2(5);
BEGIN
PV_PRD_ID := '3';
B.S_PKG.PR_MAIN (PV_PRD_ID);
COMMIT;
END;
/
commit
/
insert into tab_counts(created_dtm,
ora_database,ora_user,ora_table,cc,flg,
subj)
select sysdate,'ccenter','aim10_ccenter','s_package_run - rows',
no_of_rows,1,
'S Load Tab Run'
from s_package_run
where to_char(st_date,'YYYYMM-DD') = to_char(sysdate,'YYYYMM-DD')
and package_name = 'LOAD_TAB'
/
commit
/
insert into tab_counts(created_dtm,
ora_database,ora_user,ora_table,cc,flg,
subj)
select sysdate,'ccenter','aim10_ccenter','s_package_run - dur_min',
dur_min,2,
'S Load Tab Run'
from s_package_run
where to_char(st_date,'YYYYMM-DD') = to_char(sysdate,'YYYYMM-DD')
and package_name = 'LOAD_TAB'
/
insert into hrc_chk_mar14_24_1
select sysdate, 'B', 'COUNT 6 ', 's_load_tab',
null,null,null,null
from dual t1
/
insert into zzz
select zzz_seq.nextval,to_char(sysdate,'YYYYMMDD - HH:MI:SS AM'),
'End S Load tab',
(select trim(ruser)||' '||trim(rdbase)
from zzz_ccc where ss = 8
and rr = (select max(rr) from zzz_ccc where ss = 8)),
null,null,
null,null,null,null,
(select max(rr) from zzz_ccc where ss = 8)
from dual
/
commit
/
Then I got the following error.
ORA-00942: table or view does not exist
ORA-06512: at "B.S_PKG", line 109
ORA-06512: at "B.S_PKG", line 35
ORA-06512: at line 5
Then I searched for the package. But I could not find the exact table which gives me the error. Here is my package.
CREATE OR REPLACE PACKAGE BODY B.S_PKG is
PROCEDURE PR_Main(kseq number) IS
sql_stmnt varchar2(5000);
begin
select s_pkg_seq.nextval into dd from dual;
pkg_st_date := sysdate;
sql_stmnt:='truncate table s_msgs';
execute immediate sql_stmnt;
begin
for c_rec in (select * from s_test_1 where pkg_seq = kseq and
flg = 'as' order by pkg_ord)
loop
if substr(c_rec.run_sql,1,1) != '-' then
pkg_name := c_rec.run_sql;
PR_Msgs('*** '||c_rec.run_sql||' Started...', pkg_name||'.'||'pr_main');
else
PR_Msgs(c_rec.run_sql, pkg_name||'.'||'pr_main');
end if;
insert into s_test_3
values(sysdate,c_rec.run_sql,c_rec.pkg_seq,c_rec.pkg_ord,c_rec.prc_seq);
end loop;
end;
PR_LOAD_PRODUCT3(1,kseq);
PR_LOAD_PRODUCT3(2,kseq);
PR_LOAD_PRODUCT3(3,kseq);
PR_LOAD_PRODUCT3(4,kseq);
PR_LOAD_PRODUCT3(5,kseq);
PR_LOAD_PRODUCT3(6,kseq);
PR_LOAD_PRODUCT3(7,kseq);
PR_LOAD_PRODUCT3(8,kseq);
PR_LOAD_PRODUCT3(9,kseq);
PR_LOAD_PRODUCT3(10,kseq);
PR_LOAD_PRODUCT3(11,kseq);
begin
for c_rec in (select * from s_test_1 where pkg_seq = kseq and
flg = 'ae' order by pkg_ord)
loop
if substr(c_rec.run_sql,1,1) != '-' then
PR_Msgs('*** '||c_rec.run_sql||' End OK...', pkg_name||'.'||'pr_main');
else
PR_Msgs(c_rec.run_sql, pkg_name||'.'||'pr_main');
end if;
insert into s_test_3
values(sysdate,c_rec.run_sql,c_rec.pkg_seq,c_rec.pkg_ord,c_rec.prc_seq);
end loop;
end;
sql_stmnt:='insert into s_msgs_his select * from s_msgs where msg_ord > 0';
execute immediate sql_stmnt;
pkg_en_date := sysdate;
insert into s_package_run values (pkg_st_date,pkg_en_date,floor((pkg_en_date-pkg_st_date)*24*60),
(pkg_en_date-pkg_st_date)*24*60*60 - floor((pkg_en_date-pkg_st_date)*24*60)*60,gv_count,
pkg_name,null,dd);
end;
-- ==============================================================================================
-- ==============================================================================================
PROCEDURE PR_LOAD_PRODUCT3(pseq number, tseq number) is
sql_stmnt VARCHAR2(5000);
begin
prc_st_date := sysdate;
begin
for c_rec in (select * from s_test_1 where pkg_seq = tseq and
prc_seq = pseq and flg = 'bs' order by pkg_ord)
loop
prc_name := c_rec.run_sql;
PR_Msgs(c_rec.run_sql||' Started...', pkg_name||'.'||'pr_main');
insert into s_test_3
values(sysdate,c_rec.run_sql,c_rec.pkg_seq,c_rec.pkg_ord,c_rec.prc_seq);
end loop;
end;
begin
for c_rec in (select * from s_test_1 where pkg_seq = tseq and
prc_seq = pseq and flg = 'aa' order by pkg_ord)
loop
sql_stmnt := c_rec.run_sql;
execute immediate sql_stmnt;
insert into s_test_3
values(sysdate,c_rec.run_sql,c_rec.pkg_seq,c_rec.pkg_ord,c_rec.prc_seq);
end loop;
end;
begin
for c_rec in (select * from s_test_1 where pkg_seq = tseq and
prc_seq = pseq and flg = 'be' order by pkg_ord)
loop
if substr(c_rec.run_sql,1,1) != '-' then
PR_Msgs(c_rec.run_sql||' End OK...', pkg_name||'.'||'pr_main');
else
PR_Msgs(c_rec.run_sql, pkg_name||'.'||'pr_main');
end if;
insert into s_test_3
values(sysdate,c_rec.run_sql,c_rec.pkg_seq,c_rec.pkg_ord,c_rec.prc_seq);
end loop;
end;
select cc into gv_count
from cr2_test_2;
prc_en_date := sysdate;
insert into s_procedure_run values (prc_st_date,prc_en_date,floor((prc_en_date-prc_st_date)*24*60),
(prc_en_date-prc_st_date)*24*60*60 - floor((prc_en_date-prc_st_date)*24*60)*60,gv_count,
prc_name,pkg_name,dd);
end;
-- ==============================================================================================
-- ==============================================================================================
PROCEDURE PR_Msgs(pv_msg varchar2, pv_point varchar2) as
cc number(5);
Begin
select s_pkg2_seq.nextval into cc from dual;
insert into s_msgs values (sysdate, pv_msg, pv_point, user, '','',cc);
commit;
End;
-- ==============================================================================================
-- ==============================================================================================
END S_PKG;
/
Can anyone help me to find the error as I am new to PL SQL packages?
As far as I can tell, if you compiled the package when connected as user B and it was successful, then the only "unknown" information at that time is this:
sql_stmnt:='truncate table s_msgs';
i.e. the table you're truncating using dynamic SQL. sql_stmnt's value is a string, compiler doesn't check what's in there. But, when you actually execute it, then it finds out that there's no table s_msgs in user B's schema.
The same goes for
sql_stmnt:='insert into s_msgs_his select * from s_msgs where msg_ord > 0';
and table s_msgs_his.
As you moved everything from A to B, I guess that you should do the same with those tables. Do that and then try to run your code again.
[EDIT]
This is line 109:
for c_rec in (select * from s_test_1 where pkg_seq = tseq and
prc_seq = pseq and flg = 'aa' order by pkg_ord)
loop
sql_stmnt := c_rec.run_sql;
execute immediate sql_stmnt; --> line 109
Check what's written in S_TEST_1. Looks like some statement that is supposed to be executed dynamically, but - the table involved into it doesn't exist in schema B (or that user doesn't have privileges to use it).

SQL ORACLE error in trigger

I'm trying to create a trigger and I get the following error:
Error(24,5): PLS-00103: Found the symbol "BEGIN" when it was expected one of the following: * & - + / at loop mod remainder rem and or || multiset. I'm quite a newbie, thanks in advance!
CREATE OR replace TRIGGER ins_livro
instead OF INSERT ON viewLivros
FOR EACH ROW
DECLARE
cnt NUMBER := 10;
biggestID Number;
BEGIN
Select max(exemplar_id) into biggestID from exemplar;
INSERT INTO livro (
id_livro,
nome_livro,
id_editora,
ano,
Preco_Aluguer,
Preco_Compra,
Preco_Multa
)
VALUES (:new.id_livro,
:new.nome_livro,
:new.id_editora,
:new.ano,
:new.Preco_Aluguer,
:new.Preco_Compra,
:new.Preco_Multa
);
WHILE cnt > 0
BEGIN
SET biggestID = biggestID + 1
INSERT INTO exemplar (
id_exemplar,
id_livro
)
VALUES (
:new.biggestID,
:new.id_livro
);
SET cnt = cnt - 1
END;
END;
You are missing the loop and end loop clauses:
WHILE cnt > 0
LOOP
BEGIN
SET biggestID = biggestID + 1
INSERT INTO exemplar (
id_exemplar,
id_livro
)
VALUES (
:new.biggestID,
:new.id_livro
);
SET cnt = cnt - 1
END;
END LOOP;
You have a few mistakes in your syntax. Here it is corrected:
CREATE OR REPLACE TRIGGER ins_livro INSTEAD OF
INSERT ON viewLivros FOR EACH ROW DECLARE cnt NUMBER := 10;
biggestID NUMBER;
BEGIN
SELECT MAX(exemplar_id) INTO biggestID FROM exemplar;
INSERT
INTO livro
(
id_livro,
nome_livro,
id_editora,
ano,
Preco_Aluguer,
Preco_Compra,
Preco_Multa
)
VALUES
(
:new.id_livro,
:new.nome_livro,
:new.id_editora,
:new.ano,
:new.Preco_Aluguer,
:new.Preco_Compra,
:new.Preco_Multa
);
WHILE cnt > 0
LOOP
BEGIN
biggestID := biggestID + 1;
INSERT
INTO exemplar
(
id_exemplar,
id_livro
)
VALUES
(
biggestID,
:new.id_livro
);
cnt := cnt - 1;
END;
END LOOP;
END;
Issues:
You can't use this syntax: SET biggestID = biggestID + 1
You need to use: biggestID := biggestID + 1;
Notice the SET keyword has been removed, = has been changed to := and the line has been terminated with a semicolon.
Also, there's no such thing as :new.biggestID. That is a variable that you've defined in the trigger. It needed to be replaced by just biggestID.
Finally, the BEGIN and END around this block were replaced with LOOP and END LOOP:
SET biggestID = biggestID + 1
INSERT INTO exemplar (
id_exemplar,
id_livro
)
VALUES (
:new.biggestID,
:new.id_livro
);
SET cnt = cnt - 1

Need assistance with IF Exists then Insert

im trying to get this to run but cant figure out why its not. I am trying to create a pl/sql block that will read in 2 codes and make sure they exist before inserting:
declare
v_old_atty_id in atty_rules.attorney_id%type;
v_new_atty_id in atty_rules.attorney_id%type;
type rule_array is varray(10000) of number;
v_rule rule_array;
begin
select distinct rule_id
bulk collect into v_rule
from atty_rules
where attorney_id = v_old_atty_id
and date_activated <= sysdate
and sysdate < nvl(date_deactivated, sysdate+1);
if exists (select attorney_id
from ORG_ATTYS
where attorney_id = v_new_atty_id)
for indx in 1..v_rule.count
loop
insert into atty_rules (attorney_id,rule_id)
values (v_new_atty_id, v_rule(indx));
end loop
else
dbms_output.put_line('Doesnt exist')
end if;
end;
Any direction will help a lot, thank you.
Try this way:
select count(attorney_id)
into v_count
from ORG_ATTYS
where attorney_id = v_new_atty_id
if v_count > 0 then
for indx in 1..v_rule.count
loop
insert into atty_rules (attorney_id,rule_id)
values (v_new_atty_id, v_rule(indx));
end loop
else
dbms_output.put_line('Doesnt exist')
end if;
Maybe don't use bulk collet at all, just do it in a one SQL statement, something like this:
v_old_atty_id := ...
v_new_atty_id := ...
insert into atty_rules (attorney_id,rule_id)
select v_new_atty_id, rule_id
from (
select distinct rule_id
from atty_rules
where attorney_id = v_old_atty_id
and date_activated <= sysdate
and sysdate < nvl(date_deactivated, sysdate+1
)
WHERE exists (select attorney_id
from ORG_ATTYS
where attorney_id = v_new_atty_id);