how to add column dynamically based on user input in oracle? - oracle

how to add column dynamically based on user input in oracle?
I am generating monthly report based on from_date to to_date below is my requirement sample table
EMPLOYEE_CODE| Name | CL_TAKEN_DATE | CL_BALANCE | 01-OCT-12 | 02-OCT-12 | 03-OCT-12
100001....................John............02-OCT-12.................6
100001....................chris...........01-OCT-12.................4
Based on user input, that is, if user need the report from 01-OCT-12 TO 03-OCT-12, i need to add that dates as column in my table, like 01-OCT-12 | 02-OCT-12 | 03-OCT-12....
below is my code
create or replace
procedure MONTHLY_LVE_NEW_REPORT_demo
(
L_BUSINESS_UNIT IN SSHRMS_LEAVE_REQUEST_TRN.BUSINESS_UNIT%TYPE,
--L_LEAVE_TYPE_CODE IN SSHRMS_LEAVE_REQUEST_TRN.LEAVE_TYPE_CODE%TYPE,
L_DEPARTMENT_CODE IN VARCHAR2,
--L_MONTH IN SSHRMS_LEAVE_REQUEST_TRN.LVE_FROM_DATE%TYPE,
L_FROM_DATE IN SSHRMS_LEAVE_REQUEST_TRN.LVE_FROM_DATE%TYPE,
L_TO_DATE in SSHRMS_LEAVE_REQUEST_TRN.LVE_TO_DATE%type,
MONTHRPT_CURSOR OUT SYS_REFCURSOR
)
AS
O_MONTHRPT_CURSOR_RPT clob;
v_return_msg clob;
BEGIN
IF (L_BUSINESS_UNIT IS NOT NULL
AND L_FROM_DATE IS NOT NULL
and L_TO_DATE is not null
-- AND L_DEPARTMENT_CODE IS NOT NULL
)
THEN
OPEN MONTHRPT_CURSOR FOR
select EMPLOYEE_CODE, EMPLOYEE_NAME AS NAME, DEPARTMENT_CODE AS DEPARTMENT,DEPARTMENT_DESC, CREATED_DATE,
NVL(WM_CONCAT(CL_RANGE),'') as CL_TAKEN_DATE,
case when NVL(SUM(CL2),0)<0 then 0 else (NVL(SUM(CL2),0)) end as CL_BALANCE,
from
(
SELECT DISTINCT a.employee_code,
a.EMPLOYEE_FIRST_NAME || ' ' || a.EMPLOYEE_LAST_NAME as EMPLOYEE_NAME,
a.DEPARTMENT_CODE,
a.DEPARTMENT_DESC,
B.LEAVE_TYPE_CODE,
B.LVE_UNITS_APPLIED,
B.CREATED_DATE as CREATED_DATE,
DECODE(b.leave_type_code,'CL',SSHRMS_LVE_BUSINESSDAY(L_BUSINESS_UNIT,to_char(b.lve_from_date,'mm/dd/yyyy'), to_char(b.lve_to_date,'mm/dd/yyyy'))) CL_RANGE,
DECODE(B.LEAVE_TYPE_CODE,'CL',B.LVE_UNITS_APPLIED)CL1,
b.status
from SSHRMS_EMPLOYEE_DATA a
join
SSHRMS_LEAVE_BALANCE C
on a.EMPLOYEE_CODE = C.EMPLOYEE_CODE
and C.STATUS = 'Y'
left join
SSHRMS_LEAVE_REQUEST_TRN B
on
B.EMPLOYEE_CODE=C.EMPLOYEE_CODE
and c.EMPLOYEE_CODE = b.EMPLOYEE_CODE
and B.LEAVE_TYPE_CODE = C.LEAVE_TYPE_CODE
and B.STATUS in ('A','P','C')
and (B.LVE_FROM_DATE >= TO_DATE(L_FROM_DATE, 'DD/MON/RRRR')
and B.LVE_TO_DATE <= TO_DATE(L_TO_DATE, 'DD/MON/RRRR'))
join
SSHRMS_LEAVE_REQUEST_TRN D
on a.EMPLOYEE_CODE = D.EMPLOYEE_CODE
and D.LEAVE_TYPE_CODE in ('CL')
AND D.LEAVE_TYPE_CODE IS NOT NULL
)
group by EMPLOYEE_CODE, EMPLOYEE_NAME, DEPARTMENT_CODE, DEPARTMENT_DESC, CREATED_DATE
;
else
v_return_msg:='Field should not be empty';
end if;
END;
my code actual output
EMPLOYEE_CODE| Name | CL_TAKEN_DATE | CL_BALANCE
100001....................John............02-OCT-12.................6
100001....................chris...........01-OCT-12.................4
how to add column dynamically based on from_date to to_date?
Thanks and Regards,
Chris Jerome.

The clue is in the question:
"how to add column dynamically based on user input in oracle?"
Use dynmaic SQL. Find out more.

Related

Why is the output only the last value? Oracle loop cursor

I'm trying to output a list of the courses a professor teaches, by receiving the prof's id by parameter to my function, and showing all courses, each separated by a comma. For example, if a Professor teaches Humanities, Science and Math, I want the output to be: 'Humanities, Science, Math'. However, I'm getting just 'Math,'. It only shows the last field that it found that matched with the prof's id.
CREATE OR REPLACE FUNCTION listar_cursos(prof NUMBER) RETURN VARCHAR
IS
CURSOR C1 IS
SELECT subject.name AS name FROM subject
INNER JOIN course_semester
ON subject.id = course_semester.id_subject
WHERE course_semester.id_profesor = prof
ORDER BY subject.name;
test VARCHAR(500);
BEGIN
FOR item IN C1
LOOP
test:= item.name ||',';
END LOOP;
RETURN test;
END;
/
I am aware that listagg exists, however I do not wish to use it.
In your loop, you re-assign to the test variable, instead of appending to it. This is why, at the end of the loop, it will just hold the last value of item.name.
The assignment should instead be something like
test := test || ',' || item.name
Note also that this will leave a comma at the beginning of the string. Instead of returning test, you may want to return ltrim(test, ',').
Note that you don't need to declare a cursor explicitly. The code is easier to read (in my opinion) with an implicit cursor, as shown below. I create sample tables and data to test the function, then I show the function code and how it's used.
create table subject as
select 1 id, 'Humanities' name from dual union all
select 2 , 'Science' from dual union all
select 3 , 'Math' from dual
;
create table course_semester as
select 1 id_subject, 201801 semester, 1002 as id_profesor from dual union all
select 2 , 201702 , 1002 as id_profesor from dual union all
select 3 , 201801 , 1002 as id_profesor from dual
;
CREATE OR REPLACE FUNCTION listar_cursos(prof NUMBER) RETURN VARCHAR IS
test VARCHAR(500);
BEGIN
FOR item IN
(
SELECT subject.name AS name FROM subject
INNER JOIN course_semester
ON subject.id = course_semester.id_subject
WHERE course_semester.id_profesor = prof
ORDER BY subject.name
)
LOOP
test:= test || ',' || item.name;
END LOOP;
RETURN ltrim(test, ',');
END;
/
select listar_cursos(1002) from dual;
LISTAR_CURSOS(1002)
-----------------------
Humanities,Math,Science

PL/SQL Trigger Variable Problems

I am relatively new to PL/SQL and i am trying to create a trigger that will alert me after an UPDATE on a table Review. When it is updated I want to ge the username(User table), score(Review Table), and product name (Product Table) and print them out:
This is what I have so far:
three tables:
Review: score, userid,pid, rid
Users: userid,uname
Product: pid,pname
So Review can reference the other tables with forigen keys.
create or replace trigger userNameTrigger
after insert on review
for each row
declare
x varchar(256);
y varchar(256);
z varchar(256);
begin
select uname into x , pname into y , score into z
from review r , product p , users u
where r.pid = p.pid and r.userid = u.userid and r.rid =new.rid;
dbms_output.put_line('user: '|| X||'entered a new review for Product: '|| Y || 'with a review score of: '|| Z);
end;
The problem I am having is I cannot seem to figure out how to store the selected fields into the variables and output it correctly.
DDL:
Create Table Review
(
score varchar2(100)
, userid varchar2(100)
, pid varchar2(100)
, rid varchar2(100)
);
Create Table Users
(
userid varchar2(100)
, uname varchar2(100)
);
Create Table Product
(
pid varchar2(100)
, pname varchar2(100)
);
The first problem I can see is that you're missing a colon when you refer to new.rid. The second is that you're accessing the review table inside a row-level trigger on that same table, which will give you a mutating table error at some point; but you don't need to as all the data from the inserted row is in the new pseudorow.
create or replace trigger userNameTrigger
after insert on review
for each row
declare
l_uname users.uname%type;
l_pname product.pname%type;
begin
select u.uname into l_uname
from users u
where u.userid = :new.userid;
select p.pname
into l_pname
from product
where p.pid = :new.pid;
dbms_output.put_line('user '|| l_uname
|| ' entered a new review for product ' || l_pname
|| ' with a review score of '|| :new.score);
end;
The bigger problem is that the only person who could see the message is the user inserting tow row, which seems a bit pointless; and they would have to have output enabled in their session to see it.
If you're trying to log that so someone else can see it then store it in a table or write it to a file. As the review table can be queried anyway it seems a bit redundant though.
Having all your table columns as strings is also not good - don't store numeric values (e.g. scores, and probably the ID fields) or dates as strings, use the correct data types. It will save you a lot of pain later. You also don't seem to have any referential integrity (primary/foreign key) constraints - so you can review a product that doesn't exist, for instance, which will cause a no-data-found exception in the trigger.
It makes really no sense to use a trigger to notify themselves about changed rows. If you insert new rows into the table, then you have all info about them. Why not something like the block below instead a trigger:
create table reviews as select 0 as rid, 0 as userid, 0 as score, 0 as pid from dual where 1=0;
create table users as select 101 as userid, cast('nobody' as varchar2(100)) as uname from dual;
create table products as select 1001 as pid, cast('prod 1001' as varchar2(100)) as pname from dual;
<<my>>declare newreview reviews%rowtype; uname users.uname%type; pname products.pname%type; begin
insert into reviews values(1,101,10,1001) returning rid,userid,score,pid into newreview;
select uname, pname into my.uname, my.pname
from users u natural join products p
where u.userid = newreview.userid and p.pid = newreview.pid
;
dbms_output.put_line('user: '||my.uname||' entered a new review for Product: '||my.pname||' with a review score of: '||newreview.score);
end;
/
output: user: nobody entered a new review for Product: prod 1001 with a review score of: 10
In order to inform another session about an event you should use dbms_alert (transactional) or dbms_pipe (non transactional) packages. An example of dbms_alert:
create or replace trigger new_review_trig after insert on reviews for each row
begin
dbms_alert.signal('new_review_alert', 'signal on last rid='||:new.rid);
end;
/
Run the following block in another session (new window, worksheet, sqlplus or whatever else). It will be blocked until the registered signal is arrived:
<<observer>>declare message varchar2(400); status integer; uname users.uname%type; pname products.pname%type; score reviews.score%type;
begin
dbms_alert.register('new_review_alert');
dbms_alert.waitone('new_review_alert', observer.message, observer.status);
if status != 0 then raise_application_error(-20001, 'observer: wait on new_review_alert error'); end if;
select uname, pname, score into observer.uname, observer.pname, observer.score
from reviews join users using(userid) join products using (pid)
where rid = regexp_substr(observer.message, '\w+\s?rid=(\d+)', 1,1,null,1)
;
dbms_output.put_line('observer: new_review_alert for user='||observer.uname||',product='||observer.pname||': score='||observer.score);
end;
/
Now in your session:
insert into reviews values(2, 101,7,1001);
commit; --no alerting before commit
The another (observer) session will be finished with the output:
observer: new_review_alert for user=nobody,product=prod 1001: score=7
P.S. There was no RID in the Table REVIEW, so i'll just assume it was supposed to be PID.
create or replace trigger userNameTrigger
after insert on review
for each row
declare
x varchar2(256);
y varchar2(256);
z varchar2(256);
BEGIN
select uname
, pname
, score
INTO x
, y
, z
from review r
, product p
, users u
where r.pid = p.pid
and r.userid = u.userid
and r.PID = :new.pid;
dbms_output.put_line('user: '|| X ||'entered a new review for Product: '|| Y || 'with a review score of: '|| Z);
end userNameTrigger;
You just made a mistake on the INTO statement, you can just clump them together in one INTO.

Merge statement without affecting records where there is no change in data

I have a stored procedure that takes data from several tables and creates a new table with just the columns I want. I now want to increase performance by only attempting to insert/update rows that have at least one column of new data. For existing rows that would only receive the exact data it already has, I want to skip the update altogether for that row.
For example if a row contains the data:
ID | date | population | gdp
15 | 01-JUN-10 | 1,530,000 | $67,000,000,000
and the merge statement comes for ID 15 and date 01-JUN-10 with population 1,530,000 and gdp $67,000,000,000 then I don't want to update that row.
Here are some snippets of my code:
create or replace PROCEDURE COUNTRY (
fromDate IN DATE,
toDate IN DATE,
filterDown IN INT,
chunkSize IN INT
) AS
--cursor
cursor cc is
select c.id, cd.population_total_count, cd.evaluation_date, cf.gdp_total_dollars
from countries c
join country_demographics cd on c.id = cd.country_id
join country_financials cf on cd.country_id = cf.country_id and cf.evaluation_date = cd.evaluation_date
where cd.evaluation_date > fromDate and cd.evaluation_date < toDate
order by c.id,cd.evaluation_date;
--table
type cc_table is table of cc%rowtype;
c_table cc_table;
BEGIN
open cc;
loop -- cc loop
fetch cc bulk collect into c_table limit chunkSize; --limit by chunkSize parameter
forall j in 1..c_table.count
merge
into F_AMB_COUNTRY_INFO_16830 tgt
using (
select c_table(j).id cid,
c_table(j).evaluation_date eval_date,
c_table(j).population_total_count pop,
c_table(j).gdp_total_dollars gdp
from dual
) src
on ( cid = tgt.country_id AND eval_date = tgt.evaluation_date )
when matched then
update
set tgt.population_total_count = pop,
tgt.gdp_total_dollars = gdp
when not matched then
insert (
tgt.country_id,
tgt.evaluation_date,
tgt.population_total_count,
tgt.gdp_total_dollars )
values (
cid,
eval_date,
pop,
gdp );
exit when c_table.count = 0; --quit condition for cc loop
end loop; --end cc loop
close cc;
EXCEPTION
when ACCESS_INTO_NULL then -- catch error when table does not exist
dbms_output.put_line('Error ' || SQLCODE || ': ' || SQLERRM);
END ;
I was thinking that in the on statement, I could just say something along the lines of:
on ( cid = tgt.country_id AND eval_date = tgt.evaluation_date
AND pop != tgt.population_total_count AND gdp != tgt.gdp_total_dollars )
but surely there's a cleaner / more efficient way to do it?
The otherway you could do it is use ora_hash to get a hash of the row. So your where clause could be something like.
where ora_hash(src.col1 || src.col2 || src.col3 || src.col4) = ora_hash(src.col1 || src.col2 || src.col3 || src.col4)

PL/SQL 11g > Getting Data into a Table of Records Object

I'm trying to pull data from a complex query (it's been simplified here for review) using custom RECORD and TABLE OF RECORD data types, but I can't get data into the table due to a "PLS-00308: This construct is not allowed as the origin of an assignment" Error. I've followed the examples carefully and don't understand the problem. Can anyone point me in a direction.
here's the code
TYPE CORE_REC IS RECORD
(
OrgID CHAR(20 BYTE)
, StoreNumber VARCHAR2(200 BYTE)
, StoreName VARCHAR(200 BYTE)
, AssociateName VARCHAR2(300 BYTE)
);
TYPE CORE_REC_CURSOR IS REF CURSOR RETURN CORE_REC;
TYPE CORE_REC_TABLE IS TABLE OF CORE_REC INDEX BY BINARY_INTEGER;
FUNCTION CORE_GETCURRS (
OrgID IN CHAR
) RETURN HDT_CORE_MAIN.CORE_REC AS
CurrTable HDT_CORE_MAIN.CORE_REC;
i BINARY_INTEGER := 0;
CURSOR CurrCursor IS
WITH
CoreCurrs AS
(SELECT
busSTR.id AS OrgID
, busSTR.name AS StoreNumber
, busSTR.name2 AS StoreName
, emp.lname || ', ' || emp.fname || ' ' || emp.mname AS AssociateName
FROM tp2.tpt_company busSTR
INNER JOIN tp2.cmt_person emp
ON busSTR.ID = emp.company_id
WHERE
busSTR.id = OrgID
)
SELECT
CoreCurrs.OrgID
, CoreCurrs.StoreNumber
, CoreCurrs.StoreName
, CoreCurrs.AssociateName
FROM CoreCurrs
;
BEGIN
DBMS_OUTPUT.ENABLE(1000000);
OPEN CurrCursor;
LOOP
i := i + 1;
FETCH CurrCursor INTO CurrTable(i);
EXIT WHEN CurrCursor%NOTFOUND;
END LOOP;
CLOSE CurrCursor;
RETURN CurrTable;
END CORE_GETCURRS;
The error gets thrown at the FETCH statement.
Your variable is the wrong type, it should be:
CurrTable HDT_CORE_MAIN.CORE_REC_TABLE;
At the moment you're trying to select into an element of a record, rather than element of a table, which doesn't make sense. When it's defined as CORE_REC, referring to CurrTable(i) doesn't mean anything.

Fastest way of doing field comparisons in the same table with large amounts of data in oracle

I am recieving information from a csv file from one department to compare with the same inforation in a different department to check for discrepencies (About 3/4 of a million rows of data with 44 columns in each row). After I have the data in a table, I have a program that will take the data and send reports based on a HQ. I feel like the way I am going about this is not the most efficient. I am using oracle for this comparison.
Here is what I have:
I have a vb.net program that parses the data and inserts it into an extract table
I run a procedure to do a full outer join on the two tables into a new table with the fields in one department prefixed with '_c'
I run another procedure to compare the old/new data and update 2 different tables with detail and summary information. Here is code from inside the procedure:
DECLARE
CURSOR Cur_Comp IS SELECT * FROM T.AEC_CIS_COMP;
BEGIN
FOR compRow in Cur_Comp LOOP
--If service pipe exists in CIS but not in FM and the service pipe has status of retired in CIS, ignore the variance
If(compRow.pipe_num = '' AND cis_status_c = 'R')
continue
END IF
--If there is not a summary record for this HQ in the table for this run, create one
INSERT INTO t.AEC_CIS_SUM (HQ, RUN_DATE)
SELECT compRow.HQ, to_date(sysdate, 'DD/MM/YYYY') from dual WHERE NOT EXISTS
(SELECT null FROM t.AEC_CIS_SUM WHERE HQ = compRow.HQ AND RUN_DATE = to_date(sysdate, 'DD/MM/YYYY'))
-- Check fields and update the tables accordingly
If (compRow.cis_loop <> compRow.cis_loop_c) Then
--Insert information into the details table
INSERT INTO T.AEC_CIS_DET( Fac_id, Pipe_Num, Hq, Address, AutoUpdatedFl,
DateTime, Changed_Field, CIS_Value, FM_Value)
VALUES(compRow.Fac_ID, compRow.Pipe_Num, compRow.Hq, compRow.Street_Num || ' ' || compRow.Street_Name,
'Y', sysdate, 'Cis_Loop', compRow.cis_loop, compRow.cis_loop_c);
-- Update information into the summary table
UPDATE AEC_CIS_SUM
SET cis_loop = cis_loop + 1
WHERE Hq = compRow.Hq
AND Run_Date = to_date(sysdate, 'DD/MM/YYYY')
End If;
END LOOP;
END;
Any suggestions of an easier way of doing this rather than an if statement for all 44 columns of the table? (This is run once a week if it matters)
Update: Just to clarify, there are 88 columns of data (44 of duplicates to compare with one suffixed with _c). One table lists each field in a row that is different so one row can mean 30+ records written in that table. The other table keeps tally of the number of discrepencies for each week.
First of all I believe that your task can be implemented (and should be actually) with staight SQL. No fancy cursors, no loops, just selects, inserts and updates. I would start with unpivotting your source data (it is not clear if you have primary key to join two sets, I guess you do):
Col0_PK Col1 Col2 Col3 Col4
----------------------------------------
Row1_val A B C D
Row2_val E F G H
Above is your source data. Using UNPIVOT clause we convert it to:
Col0_PK Col_Name Col_Value
------------------------------
Row1_val Col1 A
Row1_val Col2 B
Row1_val Col3 C
Row1_val Col4 D
Row2_val Col1 E
Row2_val Col2 F
Row2_val Col3 G
Row2_val Col4 H
I think you get the idea. Say we have table1 with one set of data and the same structured table2 with the second set of data. It is good idea to use index-organized tables.
Next step is comparing rows to each other and storing difference details. Something like:
insert into diff_details(some_service_info_columns_here)
select some_service_info_columns_here_along_with_data_difference
from table1 t1 inner join table2 t2
on t1.Col0_PK = t2.Col0_PK
and t1.Col_name = t2.Col_name
and nvl(t1.Col_value, 'Dummy1') <> nvl(t2.Col_value, 'Dummy2');
And on the last step we update difference summary table:
insert into diff_summary(summary_columns_here)
select diff_row_id, count(*) as diff_count
from diff_details
group by diff_row_id;
It's just rough draft to show my approach, I'm sure there is much more details should be taken into account. To summarize I suggest two things:
UNPIVOT data
Use SQL statements instead of cursors
You have several issues in your code:
If(compRow.pipe_num = '' AND cis_status_c = 'R')
continue
END IF
"cis_status_c" is not declared. Is it a variable or a column in AEC_CIS_COMP?
In case it is a column, just put the condition into the cursor, i.e. SELECT * FROM T.AEC_CIS_COMP WHERE not (compRow.pipe_num = '' AND cis_status_c = 'R')
to_date(sysdate, 'DD/MM/YYYY')
That's nonsense, you convert a date into a date, simply use TRUNC(SYSDATE)
Anyway, I think you can use three single statements instead of a cursor:
INSERT INTO t.AEC_CIS_SUM (HQ, RUN_DATE)
SELECT comp.HQ, trunc(sysdate)
from AEC_CIS_COMP comp
WHERE NOT EXISTS
(SELECT null FROM t.AEC_CIS_SUM WHERE HQ = comp.HQ AND RUN_DATE = trunc(sysdate));
INSERT INTO T.AEC_CIS_DET( Fac_id, Pipe_Num, Hq, Address, AutoUpdatedFl, DateTime, Changed_Field, CIS_Value, FM_Value)
select comp.Fac_ID, comp.Pipe_Num, comp.Hq, comp.Street_Num || ' ' || comp.Street_Name, 'Y', sysdate, 'Cis_Loop', comp.cis_loop, comp.cis_loop_c
from T.AEC_CIS_COMP comp
where comp.cis_loop <> comp.cis_loop_c;
UPDATE AEC_CIS_SUM
SET cis_loop = cis_loop + 1
WHERE Hq IN (Select Hq from T.AEC_CIS_COMP)
AND trunc(Run_Date) = trunc(sysdate);
They are not tested but they should give you a hint how to do it.

Resources