ORA-01008: not all variables bound Oracle SQL - oracle

the below plsql code runs normally in the SQL developer window, but when i include in the package it fails
select sum(decode(refill_type,'EVD', recharge,'CUG',recharge,'EVD_BDL',recharge,'SOCH_BDL',recharge,0)) recharge_evd,
sum(decode(refill_type,'VOUCHER',recharge,0)) recharge_physical,
sum(decode(refill_type,'MOMO',recharge,'MOMO_BDL',recharge,0)) recharge_mfs,
sum(recharge) recharge_total
from
( select nvl(a.refill_type,refill_category) refill_type, recharge
from fct_daily_refill a left join ceo_refill_segmentations b on (a.segmentation_id=b.segmentation_id)
where date_key =:bdate and is_refill=1
union all
select 'MOMO_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a left join dim_bundle ax on (a.bundle_name= ax.bundle_name)
where ax.bundle_group like '%MOMO_BU%' and date_key =:bdate
union all
select 'EVD_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a
where date_key =:bdate
and upper(channel) like '%EVD%'
union all
select 'SOCH_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a
where date_key =:bdate
and upper(channel) like '%SOCH%' );

In SQL Developer, you write SQL and SQL Developer is the client, so it does the handling of the results that come back, plus the handling of getting your inputs into the query.
In a package, the package is now responsible for that, both getting values into the SQL and dealing with the results that come back from the SQL. Thus your SQL might end up looking like:
procedure MY_PROC(bdate in date) is
begin
for i in (
select sum(decode(refill_type,'EVD', recharge,'CUG',recharge,'EVD_BDL',recharge,'SOCH_BDL',recharge,0)) recharge_evd,
sum(decode(refill_type,'VOUCHER',recharge,0)) recharge_physical,
sum(decode(refill_type,'MOMO',recharge,'MOMO_BDL',recharge,0)) recharge_mfs,
sum(recharge) recharge_total
from
( select nvl(a.refill_type,refill_category) refill_type, recharge
from fct_daily_refill a left join ceo_refill_segmentations b on (a.segmentation_id=b.segmentation_id)
where date_key =bdate and is_refill=1
union all
select 'MOMO_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a left join dim_bundle ax on (a.bundle_name= ax.bundle_name)
where ax.bundle_group like '%MOMO_BU%' and date_key =bdate
union all
select 'EVD_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a
where date_key =bdate
and upper(channel) like '%EVD%'
union all
select 'SOCH_BDL' refill_type, trans_amt recharge
from fct_cdr_subscriptions a
where date_key =bdate
and upper(channel) like '%SOCH%' )
)
loop
--
-- do what you need to do with the query output, which will be in:
--
-- i.recharge_evd, i.recharge_physical, i.recharge_mfs, i.recharge_total
--
end loop;
end;

Related

PL/SQL FOR Loop Error when Populating Dimension Table

I am populating a dimension table named TIMES with data from an OLTP Table called SALES with the following code:
CREATE TABLE TIMES
(saleDay DATE PRIMARY KEY,
dayType VARCHAR(50) NOT NULL);
BEGIN
FOR rec IN
(SELECT saleDate, CASE WHEN h.hd IS NOT NULL THEN 'Holiday'
WHEN to_char(saleDate, 'd') IN (1,7) THEN 'Weekend'
ELSE 'Weekday' END dayType
FROM SALES s LEFT JOIN
(SELECT '01.01' hd FROM DUAL UNION ALL
SELECT '15.01' FROM DUAL UNION ALL
SELECT '19.01' FROM DUAL UNION ALL
SELECT '28.05' FROM DUAL UNION ALL
SELECT '04.07' FROM DUAL UNION ALL
SELECT '08.10' FROM DUAL UNION ALL
SELECT '11.11' FROM DUAL UNION ALL
SELECT '22.11' FROM DUAL UNION ALL
SELECT '25.12' FROM DUAL) h
ON h.hd = TO_CHAR(s.saleDate, 'dd.mm'))
LOOP
INSERT INTO TIMES VALUES rec;
END LOOP;
END;
/
When I run this, I'm getting the errors ORA-00001 (Unique Constraint Violation) and ORA-06512. I believe this is happening because the code is trying to input multiple dates (some of which are the same) into PK for my TIMES Dimension Table (saleDay). How would I implement a clause into this loop so it will only populate one instance of each saleDate into the saleDay PK so there isn't a violation?
For instance, If there are three rows in the SALES table where the saleDate is 2015-10-10, the code should only populate ONE instance of 2015-10-10 into the saleDay PK. I'm thinking the direction I should head is to implement a WHILE clause, however I'm not 100% sure on how that would work since this code is also using CASE to determine whether the saleDay was a Holiday, Weekday, or Weekend and populating the result into the dayType column.
Adding DISTINCT as suggested in a Comment below your question is one way to solve the problem.
The following approach may be more efficient:
for rec in (select distinct saledate from sales)
loop
insert into times (saleday, daytype) values
(rec.saledate, CASE .......);
end loop;
That is: put the CASE expression in the INSERT statement, not in the definition of the (implicit) cursor. There is no reason to compute the CASE expression multiple times for the same date, which may appear many times in the SALES table. There is no reason for the CASE expression to be part of the cursor, either. The CASE expression can use an IN condition (case when to_char(rec.saledate, 'dd.mm') in ('01.01', '15.01', ....) then 'Holiday' when .......)
Unless, of course, the homework problem specifically instructs you to use a left outer join....... :-(
Adding DISTINCT resolved this. Originally thought DISTINCT would negatively impact the CASE but it doesn't. Thanks to I3rutt for pointing this out.
BEGIN
FOR rec IN
(SELECT DISTINCT saleDate, CASE WHEN h.hd IS NOT NULL THEN 'Holiday'
WHEN to_char(saleDate, 'd') IN (1,7) THEN 'Weekend'
ELSE 'Weekday' END dayType
FROM SALES s LEFT JOIN
(SELECT '01.01' hd FROM DUAL UNION ALL
SELECT '15.01' FROM DUAL UNION ALL
SELECT '19.01' FROM DUAL UNION ALL
SELECT '28.05' FROM DUAL UNION ALL
SELECT '04.07' FROM DUAL UNION ALL
SELECT '08.10' FROM DUAL UNION ALL
SELECT '11.11' FROM DUAL UNION ALL
SELECT '22.11' FROM DUAL UNION ALL
SELECT '25.12' FROM DUAL) h
ON h.hd = TO_CHAR(s.saleDate, 'dd.mm'))
LOOP
INSERT INTO TIMES VALUES rec;
END LOOP;
END;
/

Query taking long when i use user defined function with order by in oracle select

I have a function, which will get greatest of three dates from the table.
create or replace FUNCTION fn_max_date_val(
pi_user_id IN number)
RETURN DATE
IS
l_modified_dt DATE;
l_mod1_dt DATE;
l_mod2_dt DATE;
ret_user_id DATE;
BEGIN
SELECT MAX(last_modified_dt)
INTO l_modified_dt
FROM table1
WHERE id = pi_user_id;
-- this table contains a million records
SELECT nvl(MAX(last_modified_ts),sysdate-90)
INTO l_mod1_dt
FROM table2
WHERE table2_id=pi_user_id;
-- this table contains clob data, 800 000 records, the table 3 does not have user_id and has to fetched from table 2, as shown below
SELECT nvl(MAX(last_modified_dt),sysdate-90)
INTO l_mod2_dt
FROM table3
WHERE table2_id IN
(SELECT id FROM table2 WHERE table2_id=pi_user_id
);
execute immediate 'select greatest('''||l_modified_dt||''','''||l_mod1_dt||''','''||l_mod2_dt||''') from dual' into ret_user_id;
RETURN ret_user_id;
EXCEPTION
WHEN OTHERS THEN
return SYSDATE;
END;
this function works perfectly fine and executes within a second.
-- random user_id , just to test the functionality
SELECT fn_max_date_val(100) as max_date FROM DUAL
MAX_DATE
--------
27-02-14
For reference purpose i have used the table name as table1,table2 and table3 but my business case is similar to what i stated below.
I need to get the details of the table1 along with the highest modified date among the three tables.
I did something like this.
SELECT a.id,a.name,a.value,fn_max_date_val(id) as max_date
FROM table1 a where status_id ='Active';
The above query execute perfectly fine and got result in millisecods. But the problem came when i tried to use order by.
SELECT a.id,a.name,a.value,a.status_id,last_modified_dt,fn_max_date_val(id) as max_date
FROM table1 where status_id ='Active' a
order by status_id desc,last_modified_dt desc ;
-- It took almost 300 seconds to complete
I tried using index also all the values of the status_id and last_modified, but no luck. Can this be done in a right way?
How about if your query is like this?
select a.*, fn_max_date_val(id) as max_date
from
(SELECT a.id,a.name,a.value,a.status_id,last_modified_dt
FROM table1 where status_id ='Active' a
order by status_id desc,last_modified_dt desc) a;
What if you don't use the function and do something like this:
SELECT a.id,a.name,a.value,a.status_id,last_modified_dt x.max_date
FROM table1 a
(
select max(max_date) as max_date
from (
SELECT MAX(last_modified_dt) as max_date
FROM table1 t1
WHERE t1.id = a.id
union
SELECT nvl(MAX(last_modified_ts),sysdate-90) as max_date
FROM table2 t2
WHERE t2.table2_id=a.id
...
) y
) x
where a.status_id ='Active'
order by status_id desc,last_modified_dt desc;
Syntax might contain errors, but something like that + the third table in the derived table too.

Ora-00932 - expected NUMBER got -

I have been running the below query without issue:
with Nums (NN) as
(
select 0 as NN
from dual
union all
select NN+1 -- (1)
from Nums
where NN < 30
)
select null as errormsg, trunc(sysdate)-NN as the_date, count(id) as the_count
from Nums
left join
(
SELECT c1.id, trunc(c1.c_date) as c_date
FROM table1 c1
where c1.c_date > trunc(sysdate) - 30
UNION
SELECT c2.id, trunc(c2.c_date)
FROM table2 c2
where c2.c_date > trunc(sysdate) -30
) x1
on x1.c_date = trunc(sysdate)-Nums.NN
group by trunc(sysdate)-Nums.NN
However, when I try to pop this in a proc for SSRS use:
procedure pr_do_the_thing (RefCur out sys_refcursor)
is
oops varchar2(100);
begin
open RefCur for
-- see above query --
;
end pr_do_the_thing;
I get
Error(): PL/SQL: ORA-00932: inconsistent datatypes: expected NUMBER got -
Any thoughts? Like I said above, as a query, there is no issue. As a proc, the error appears at note (1) int eh query.
This seems to be bug 18139621 (see MOS Doc ID 2003626.1). There is a patch available, but if this is the only place you encounter this, it might be simpler to switch to a hierarchical query:
with Nums (NN) as
(
select level - 1
from dual
connect by level <= 31
)
...
You could also calculate the dates inside the CTE (which also fails with a recursive CTE):
with Dates (DD) as
(
select trunc(sysdate) - level + 1
from dual
connect by level <= 31
)
select null as errormsg, DD as the_date, count(id) as the_count
from Dates
left join
(
SELECT c1.id, trunc(c1.c_date) as c_date
FROM table1 c1
where c1.c_date > trunc(sysdate) - 30
UNION
SELECT c2.id, trunc(c2.c_date)
FROM table2 c2
where c2.c_date > trunc(sysdate) -30
) x1
on x1.c_date = DD
group by DD;
I'd probably organise it slightly differently, so the subquery doesn't limit the date range directly:
with dates (dd) as
(
select trunc(sysdate) - level + 1
from dual
connect by level <= 31
)
select errormsg, the_date, count(id) as the_count
from (
select null as errormsg, d.dd as the_date, c1.id
from dates d
left join table1 c1 on c1.c_date >= d.dd and c1.c_date < d.dd + 1
union all
select null as errormsg, d.dd as the_date, c2.id
from dates d
left join table2 c2 on c2.c_date >= d.dd and c2.c_date < d.dd + 1
)
group by errormsg, the_date;
but as always with these things, check the performance of each approach...
Also notice that I've switched from union to union all. If an ID could appear more than once on the same day, in the same table or across both tables, then the counts will be different - you need to decide whether you want to count them once or as many times as they appear. That applies to your original query too.

Oracle Drop Table with YYYMMDD and YYYMMDD_HHMMSS

I have some tables end with date (YYYYMMDD), some end with HHMMSS:
INVENLEVEL_20160419
INVENLEVEL_20160419_120232 <-optional to exist
INVENLEVEL_20160425
INVENLEVEL_20160426
INVENLEVEL_20160426_032112 <-optional to exist
I need to keep tables within 7 days and drop other INVENLEVEL TABLES.
Expected Results, the following 2 tables deleted:
INVENLEVEL_20160419
INVENLEVEL_20160419_120232
Im able to drop for tables with date, but not the one with HHMMSS.
FOR x IN ( SELECT TABLE_NAME
FROM USER_TABLES
WHERE REGEXP_LIKE(TABLE_NAME, 'INVENLEVEL_[[:digit:]]{8}')
AND TO_DATE(SUBSTR(TABLE_NAME, -8), 'yyyymmdd') <= TRUNC(SYSDATE) - 7
) LOOP
EXECUTE IMMEDIATE 'DROP TABLE ' ||
x.TABLE_NAME ||
' PURGE';
How can i also drop for the table with HHMMSS also? Please note that tables with HHMMSS is optional to exist, means, sometimes we have it, sometime not.
Something like this, perhaps:
with sample_data as (select 'INVENLEVEL_20160419' table_name from dual union all
select 'INVENLEVEL_20160419_120232' table_name from dual union all
select 'INVENLEVEL_20160425' table_name from dual union all
select 'INVENLEVEL_20160426' table_name from dual union all
select 'INVENLEVEL_20160426_032112' table_name from dual union all
select 'NEW_20160426_032112' table_name from dual union all
select 'FRED' table_name from dual)
---- end of mimicking your data; see SQL below
select table_name,
to_date(substr(table_name, 12, 8), 'yyyymmdd') dt
from sample_data
where REGEXP_LIKE(TABLE_NAME, '^INVENLEVEL_[[:digit:]]{8}($|_[[:digit:]]{6})')
and to_date(substr(table_name, 12, 8), 'yyyymmdd') <= trunc(sysdate -7);
TABLE_NAME DT
-------------------------- ----------
INVENLEVEL_20160419 19/04/2016
INVENLEVEL_20160419_120232 19/04/2016
Obviously, you wouldn't need the sample_data subquery - I just used that in order to have data for the SQL to work against. You'd query your user_tables instead.
I amended your regexp to additionally check that it had either reached the end of the string after the 8 digits or there was another underscore followed by 6 digits.
Then I amended your substr to check for the 8 characters from the 12th position, in order to get the date - you have to do it like this, since if you use the end of the string as you had been doing, the date is not necessarily 8 characters from the end.

How to write a table literal in Oracle?

A table with one column and one row can be created with:
select 'create' as col from dual;
This can be used to build table joins:
with
a as (select 'create' as ac from dual),
b as (select 'delete' as bc from dual)
select * from a left outer join b on (ac = bc);
Now I would like to have two rows. I did it in this way:
select 'create' as col from dual
union
select 'delete' as col from dual;
But is there a more compact notation for this? I tried
select ('create', 'delete') as col from dual;
but it does not work.
You can use collection type and TABLE operator, for example (works in Oracle 10g):
SQL> SELECT column_value FROM TABLE(SYS.ODCIVARCHAR2LIST('abc', 'def', 'ghi'));
COLUMN_VALUE
--------------------------------------------------------------------------------
abc
def
ghi
A couple of ways to generate rows. You could use rownum against a table with a larger number of rows:
SELECT roWnum AS a
FROM user_objects
WHERE rownum <= 3
You could use a hierarchical query:
SELECT level AS a
FROM dual
CONNECT BY LEVEL <= 3
EDIT: change int sequence to alpha sequence:
SELECT CHR( ASCII('a') + level - 1 )
FROM dual
CONNECT BY LEVEL <= 3

Resources