Help for pl/sql block
need help on this to performance better.
DECLARE
FILE_READ UTL_FILE.FILE_TYPE;
LOCATION VARCHAR2(128):='D:\PLSQL';
FILENAME VARCHAR2(128):='TEST.txt';
OPEN_MODE VARCHAR2(128):='r';
V_LINE VARCHAR2(128);
V_ORDERCODE CHAR(15);
V_REST CHAR(100);
V_OWNERCODE CHAR(5);
CURSOR C_ORD IS
SELECT ORD.ORDERID,ORD.OWNERID
FROM ORDERS ORD,OWNERS OWN
WHERE ORD.ORDERCODE=V_ORDERCODE
AND ORD.OWNERID=OWN.OWNERID
AND OWN.OWNERCODE=V_OWNERCODE
AND ORD.STATUS=10
ORDER BY ORD.SEQ DESC;
R_ORD C_ORD%ROWTYPE;
BEGIN
FILE_READ:=UTL_FILE.FOPEN(LOCATION,FILENAME,OPEN_MODE);
LOOP
BEGIN
UTL_FILE.GET_LINE(FILE_READ,V_LINE);
EXCEPTION
WHEN NO_DATA_FOUND THEN
EXIT;
END;
V_OWNERCODE:=RTRIM(SUBSTR(V_LINE,0,5));
V_ORDERCODE:=SUBSTR(V_LINE,7,15);
V_REST:=SUBSTR(V_LINE,23,LENGTH(RTRIM(LTRIM(V_LINE))));
OPEN C_ORD;
FETCH C_ORD INTO R_ORD;
IF C_ORD%FOUND THEN
UPDATE ORDERS SET UNDEF10=RTRIM(V_REST) WHERE ORDERCODE=V_ORDERCODE AND OWNERID=R_ORD.OWNERID;
END IF;
CLOSE C_ORD;
END LOOP;
UTL_FILE.FCLOSE(FILE_READ);
EXCEPTION
WHEN UTL_FILE.INVALID_MODE THEN
RAISE_APPLICATION_ERROR(-20001,'INVALID_MODE');
WHEN UTL_FILE.READ_ERROR THEN
RAISE_APPLICATION_ERROR(-20002,'READ_ERROR');
WHEN UTL_FILE.INVALID_PATH THEN
RAISE_APPLICATION_ERROR(-20003,'INVALID_PATH');
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
RAISE_APPLICATION_ERROR(-20004,'INVALID_FILEHANDLE');
WHEN UTL_FILE.INVALID_OPERATION THEN
RAISE_APPLICATION_ERROR(-20005,'INVALID_OPERATION');
WHEN UTL_FILE.WRITE_ERROR THEN
RAISE_APPLICATION_ERROR(-20006,'WRITE_ERROR');
WHEN UTL_FILE.INTERNAL_ERROR THEN
RAISE_APPLICATION_ERROR(-20007,'INTERNAL_ERROR');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20008,SQLERRM);
END;
My obersvations for poor performance (although you have not defined what is "poor")
1. Why ORDER BY in cursor ?
2. Why CURSOR itself ?
It seems to me that all you are doing is checking whether the SQL (in cursor) returns any data. If yes, yo are updating ORDERS table. You should be able to eliminate cursor entirely. That will save all processing on cursor.
If you can explain (in english) what you are trying to achieve, I may be able to provide better solution.
Similar Messages
-
SQL logic help for pl/sql block
Hi All,
I need your suggestions and comments for the below issue:
I have two tables: table A and table B
Table A has two columns as id and counts:
Id Counts
99 10
999 13
9999 7
Table B has two columns as Id and order:
Id Order
99 1
999 2
9999 3
We need to update Order in Table B such that Id having highest count in table A has Order as 1 in table B and it keep on increasing the order for other Ids based on decreasing counts in table A. This will be like a job which will run daily and look for counts in table A and update Order in table B according to it.
It seems to be simple but i am not getting it. Please help me out of this by writing some PL/SQL block.
I will really appreciate your all comments and responses.
Regards
DevHi,
Keen2Learn wrote:
Hi All,
I am really greatful to all fo you for all your replies and comments. I change ORDER table to ORDERS. All you replies worked for me but there is some slight change in scenario which i need to discuss with you all.
E.g: Table A has 10 rows like below:
Id Counts Type
99 10 A
999 13 A
9999 7 C
99 4 B
999 2 C
88 2 A
77 1 C
777 3 B
777 5 A
888 2 CIf you'd like help, please post CREATE TABLE and INSERT statements for your sample data (including table b as it is before the UPDATE or MERGE).
I populate data in Orders column Table B based on id, by grouping sum of counts for that id in table A.
Id 999 has highest sum(count) as 15, so it has orders as 1 in Table B and do same for descending counts for each Id.
Table B has 5 rows like below:
Id Orders
99 2
999 1
88 4
777 3
555 5
Assume Table B as static(no new record comes in it) but only its Orders changes for each Id based on counts for that Id in Table A. As you see, Table B has id 555 which is not in Table A, so we need to update its orders to the highest number by taking its Count as 0(zero). Sorry, it's unclear what you want to do.
Post what you'd like table b to look like after the UPDATE or MERGE.
Right now i am doing it like this:
declare
cursor c1 is
select Id, SUM (COUNT), RANK () OVER (ORDER BY SUM (COUNT)) rnk
from TableA AND Id IN (SELECT Id FROM TableB)
GROUP BY Id
ORDER BY rnk DESC;
i NUMBER := 1;
begin
for curr in c1
loop
update TableB
set orders = i
where id = curr.id;
i := i + 1;
end loop;
end;I'm not sure what you're trying to do, but I'll bet you don't need PL/SQL to do it. Use a single UPDATE or MERGE statement (inside PL/SQL if necessary).
But it is not updating orders for Id 555 in TableB.There is no row for id=555 in table b, and, according to your requirements, there never will be, because "Table B as static(no new record comes in it)". It's behaving exactly as you said you wanted it to. What's the problem?
Please provide your suggesstions on what needs to be done to take care of this scenario. I will really appreciate your all suggesstions and comments. Please let me know if need some more explanation.Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using. -
Cell Offload will Happen for pl/sql Block with variables
Hello Experts,
i am working on procedures on exadata now. i was confused with cell offload in exadata. somehow offload is not happening when i ran the sql statement in in pl/sql block with variables.
here are my findings.
when i ran insert into from select with values at toad, my query response time is very good. the total process is completed in less than a minute.
i checked offload is happening.
same sql statement is placed in plsql block with variable, procedure is taking lot of time and it is not completing. this case offload is not happening.
is it true, if i use variables in pl/sql block will not use cell offload and smart scan?
if yes, what is the work around.
Thanks
#! PavanHello Marc,
Thanks for quick response.
when i ran the query with literals in toad session i am getting response.
when i run it with pl/sql block , block is not completing at all.
here is the plsql block:
My Apologies for sending big code,with out proper format.
DECLARE
P_BUSINESS_DATE DATE;
P_BATCH_ID NUMBER;
UTC_OFFSET NUMBER;
BEGIN
P_BUSINESS_DATE := to_date('02/01/2012', 'MM/DD/YYYY');
P_BATCH_ID := 1;
UTC_OFFSET := 0;
INSERT /*+ APPEND */ INTO UPL_CLIENT_tbl
( reportdate,
LastName,
FirstName,
MiddleInitial,
AccountNumber,
Address,
City,
State,
Zip,
HomePhone,
WorkPhone,
BirthDate,
Age,
Sex,
NumberOfChildren,
Occupation,
LeadSource,
Consultant,
ProgramDirector,
CallTaker,
LeadDate,
FirstVisitDate,
LastVisitDate,
BillType,
ClientType,
PreviousClientType,
AppointmentDate,
DoctorLetterRequired,
OneYearPermStabilizationDate,
UnlimitedPermStabilizationDate,
MaritalStatus,
ReferrerName,
ReferrerCentreID,
CentreID,
PaymentDateOne,
PaymentAmountOne,
PaymentDateTwo,
PaymentAmountTwo,
PaymentDateThree,
PaymentAmountThree,
PaymentDateFour,
PaymentAmountFour,
LibraryPurchased,
BalanceDue,
FoodNSFBalance,
ProductNSFBalance,
ProgramNSFBalance,
StartWeight,
CurrentWeight,
GoalWeight,
Height,
DateGoalWeightAchieved,
DateSuccessPlusPurchased,
ReturnToActiveDate,
VersionNumber,
HalfWayDate,
LastLSCDate,
LastUpdatedDate,
VitaminWaiverSigned,
LastSupplementPurchaseDate,
LastSupplementCodePurchased,
LastTotalSupplementSupplyCycle,
LastAddtlSupplPurchaseDate,
LastAddtlSupplCodePurchased,
LastAddtlSupplSupplyCycle,
DiabetesClient,
DietControlled,
TakingOralMed,
TakingInsulin,
EmailId,
CTADate,
RWLDate,
Address2)
(SELECT /*+ full(S_CONTACT) full(REFERRER) full(Consultant) full(ProgramDirector) full(CallTaker) full(S_CONTACT_X) full(a) full(a2) full (a3) */ distinct p_business_date reportdate,
SUBSTR(S_CONTACT.LAST_NAME,1,25) AS LastName,
SUBSTR(S_CONTACT.FST_NAME,1,25) AS FirstName,
SUBSTR(S_CONTACT.MID_NAME,1,1) AS MiddleInitial,
S_CONTACT.X_JC_ACNT_NUM + 900000000 AS AccountNumber,
SUBSTR(S_ADDR_PER.ADDR,1,40) AS ADDRESS,
SUBSTR(S_ADDR_PER.CITY,1,20) AS City,
S_ADDR_PER.STATE AS State,
SUBSTR(S_ADDR_PER.ZIPCODE,1,15) AS Zip,
SUBSTR(REPLACE(S_CONTACT.HOME_PH_NUM,'-',''),1,10) AS HomePhone,
SUBSTR(REPLACE(S_CONTACT.WORK_PH_NUM,'-',''),1,10) AS WorkPhone,
S_CONTACT.BIRTH_DT AS BirthDate,
CASE WHEN FLOOR((p_business_date - S_CONTACT.BIRTH_DT)/360) < 0 THEN NULL ELSE FLOOR((p_business_date - S_CONTACT.BIRTH_DT)/360) END AS AGE,
S_CONTACT.SEX_MF AS SEX,
NULL AS NumberOfChildren,
S_CONTACT_X.ATTRIB_34 AS OCCUPATION,
CASE WHEN SUBSTR(S_CONTACT_X.ATTRIB_37,1,4)='Othe' THEN 'Othr'
WHEN SUBSTR(S_CONTACT_X.ATTRIB_37,1,4)='Inte' THEN 'Intr'
WHEN SUBSTR(S_CONTACT_X.ATTRIB_37,1,4)='Prin' THEN 'News'
WHEN SUBSTR(S_CONTACT_X.ATTRIB_37,1,4)='Gues' THEN 'Gst'
ELSE SUBSTR(S_CONTACT_X.ATTRIB_37,1,4) END AS LeadSource,
SUBSTR(Consultant.EMP_NUM,1,10) AS CONSULTANT,
ProgramDirector.EMP_NUM AS ProgramDirector,
CallTaker.EMP_NUM CallTaker,
S_CONTACT.X_LEAD_DT AS LeadDate,
LEAST(nvl(S_CONTACT.X_LAST_CONSULTATION_DATE,O.FirstPurchaseDate ), nvl(O.FirstPurchaseDate,S_CONTACT.X_LAST_CONSULTATION_DATE+1) ) AS FirstVisitDate, --X_LAST_CONSULTATION_DATE stores the performed date or the legacy client firstvisitdate
GREATEST(nvl(S_CONTACT_XM.X_CONSULTATION_DT ,S_CONTACT_X.ATTRIB_29), nvl(S_CONTACT_X.ATTRIB_29, S_CONTACT_XM.X_CONSULTATION_DT-1) ) AS LastVisitDate,
CASE WHEN S_CONTACT.X_INSTALLMENT_BALANCE > 0 THEN 'B' ELSE NULL END AS BillType,
ct.current_client_type ClientType,
SUBSTR(ct.saved_client_type,1,1) PreviousClientType,
S_CONTACT.LAST_CREDIT_DT AS AppointmentDate,
CASE WHEN a.X_DR_LETTER_STATUS IS NOT NULL THEN 'Y' ELSE 'N' END AS DoctorLetterRequired,
NULL AS OneYearPermStabilizationDate,
DECODE(S_PROD_INT.X_PROGRAM_CLASSIFICATION,'Premium',a.START_DT ,NULL) AS UnlimitedPermStabilizationDate,
SUBSTR(S_CONTACT.MARITAL_STAT_CD,1,1) AS MaritalStatus,
SUBSTR(REFERRER.FST_NAME ||' '|| REFERRER.LAST_NAME,1,34) AS ReferrerName,
ORGEXT_REF.LOC AS ReferrerCentreID,
S_ORG_EXT.LOC AS CentreID,
NULL AS PaymentDateOne,
NULL AS PaymentAmountOne,
NULL AS PaymentDateTwo,
NULL AS PaymentAmountTwo,
NULL AS PaymentDateThree,
NULL AS PaymentAmountThree,
NULL AS PaymentDateFour,
NULL AS PaymentAmountFour,
NULL AS LibraryPurchased,
nvl(S_CONTACT.X_INSTALLMENT_BALANCE,0) + nvl(S_CONTACT.X_PREPAID_BALANCE,0) AS BalanceDue, -- Changed operation from (-) prepaid to (+) prepaid since the sign was flipped in OLTP.
NULL AS FoodNSFBalance,
NULL AS ProductNSFBalance,
NULL AS ProgramNSFBalance,
a2.X_START_WEIGHT AS StartWeight,
a2.X_CURRENT_WEIGHT AS CurrentWeight,
a2.X_GOAL_WEIGHT AS GoalWeight,
a3.X_HEIGHT AS Height,
a2.X_FAXSENT_DATETIME DateGoalWeightAchieved,
DECODE(S_PROD_INT.X_PROGRAM_CLASSIFICATION,'Premium',a.START_DT,NULL) AS DateSuccessPlusPurchased,
CASE WHEN A2.ARCHIVE_FLG = 'N' THEN a2.START_DT ELSE NULL END AS ReturnToActiveDate,
600 VersionNumber,
a2.X_FAXRECV_DATETIME AS HalfWayDate,
NULL AS LastLSCDate,
TRUNC(S_CONTACT.LAST_UPD-UTC_OFFSET/24) AS LastUpdatedDate,
NULL AS VitaminWaiverSigned,
LastSupplementPurchaseDate,
LastSupplementCodePurchased,
LastTotalSupplementSupplyCycle,
LastAddtlSupplPurchaseDate,
LastAddtlSupplCodePurchased,
LastAddtlSupplSupplyCycle,
CASE WHEN (a.X_DIABETES_NO_MEDS_FLG='Y' OR a.X_DIABETES_ORAL_MEDS_FLG = 'Y' OR a.X_DIABETES_ON_INSULIN_FLG = 'Y') THEN 'Y' ELSE 'N' END AS DiabetesClient,
DECODE(a.X_DIABETES_NO_MEDS_FLG,'Y','Y','N') AS DietControlled,
a.X_DIABETES_ORAL_MEDS_FLG AS TakingOralMed,
a.X_DIABETES_ON_INSULIN_FLG AS TakingInsulin,
S_CONTACT.EMAIL_ADDR AS EmailId,
NULL CTADATE,
NULL RWLDATE,
SUBSTR(S_ADDR_PER.ADDR_LINE_2,1,40) AS Address2
FROM S_CONTACT,
S_CONTACT REFERRER,
S_CONTACT Consultant,
S_CONTACT ProgramDirector,
S_CONTACT CallTaker,
S_CONTACT_X,
(SELECT /*+ parallel full(S_CONTACT_XM) */ PAR_ROW_ID, attrib_05, MAX(X_CONSULTATION_DT) AS X_CONSULTATION_DT FROM S_CONTACT_XM
WHERE (S_CONTACT_XM.last_upd_by < '1-14WD'
or S_CONTACT_XM.last_upd_by > '1-14WD')
AND S_CONTACT_XM.ATTRIB_05 IN (SELECT row_id FROM S_ORG_EXT WHERE S_ORG_EXT.ACCNT_TYPE_CD IN ('Corporate Centre','Franchise Centre')) LOC IN (SELECT centreid FROM UPL_LIVE_CENTRES WHERE LIVE = 'Y' AND BATCHID = p_batch_id)) where S_ORG_EXT.ACCNT_TYPE_CD IN ('Corporate Centre','Franchise Centre')) --
GROUP BY PAR_ROW_ID, attrib_05) S_CONTACT_XM,
(SELECT CONTACT_ID, ACCNT_ID,
MAX(LastSupplementPurchaseDate) AS LastSupplementPurchaseDate,
MAX(LastSupplementCodePurchased) AS LastSupplementCodePurchased,
MAX(LastTotalSupplementSupplyCycle) AS LastTotalSupplementSupplyCycle,
MAX(LastAddtlSupplPurchaseDate) AS LastAddtlSupplPurchaseDate,
MAX(LastAddtlSupplCodePurchased) AS LastAddtlSupplCodePurchased,
MAX(LastAddtlSupplSupplyCycle) AS LastAddtlSupplSupplyCycle,
MIN(FirstPurchaseDate) AS FirstPurchaseDate,
MAX(LastPurchaseDate) AS LastPurchaseDate
FROM (
SELECT /*+ parallel full(S_ORDER) full(S_ORDER_XM) */ S_ORDER.CONTACT_ID AS CONTACT_ID,S_ORDER.ACCNT_ID,
NULL AS LastSupplementPurchaseDate,
NULL AS LastSupplementCodePurchased,
NULL AS LastTotalSupplementSupplyCycle,
NULL AS LastAddtlSupplPurchaseDate,
NULL AS LastAddtlSupplCodePurchased,
NULL AS LastAddtlSupplSupplyCycle,
(S_ORDER_XM.X_BUSINESS_DATE) FirstPurchaseDate,
(S_ORDER_XM.X_BUSINESS_DATE) LastPurchaseDate
FROM S_ORDER,S_ORDER_XM
WHERE S_ORDER.ROW_ID = S_ORDER_XM.PAR_ROW_ID
AND S_ORDER.STATUS_CD IN ('Complete', 'Submitted', 'Ready')
AND TRUNC(S_ORDER_XM.X_BUSINESS_DATE - UTC_OFFSET/24) <= (p_business_date)
--GROUP BY S_ORDER.CONTACT_ID
UNION ALL
SELECT /*+ parallel full(S_ORDER) full (S_ORDER_ITEM) */ S_ORDER.CONTACT_ID AS CONTACT_ID,S_ORDER.ACCNT_ID,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '931' THEN S_ORDER.CREATED ELSE NULL END) AS LastSupplementPurchaseDate,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '931' THEN 931 ELSE NULL END) AS LastSupplementCodePurchased,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '931' THEN 7 ELSE NULL END) AS LastTotalSupplementSupplyCycle,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '920' THEN S_ORDER.CREATED ELSE NULL END) AS LastAddtlSupplPurchaseDate,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '920' THEN 920 ELSE NULL END) AS LastAddtlSupplCodePurchased,
(CASE WHEN SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) = '920' THEN 28 ELSE NULL END) AS LastAddtlSupplSupplyCycle,
NULL FirstPurchaseDate,
NULL LastPurchaseDate
FROM S_ORDER,S_ORDER_ITEM, S_PROD_INT
WHERE S_ORDER_ITEM.PROD_ID = S_PROD_INT.ROW_ID
AND S_ORDER.ROW_ID = S_ORDER_ITEM.ORDER_ID
AND S_ORDER_ITEM.qty_req <> 0
AND s_order.created_by <> '1-14WD'
AND S_ORDER_ITEM.PAR_ORDER_ITEM_ID is null
AND (S_ORDER_ITEM.PAR_ORDER_ITEM_ID is null
OR EXISTS (select 1 from S_ORDER_ITEM i2,s_prod_int p
where i2.row_id = S_ORDER_ITEM.PAR_ORDER_ITEM_ID
and SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) IN ('931','920')
and i2.prod_id = p.row_id
AND S_ORDER.status_cd in ('Complete', 'Submitted', 'Ready')
and SUBSTR(SUBSTR(S_PROD_INT.PART_NUM,1,INSTR(S_PROD_INT.PART_NUM,'-',1,1)-1),2,4) IN ('931','920')
GROUP BY CONTACT_ID,ACCNT_ID) O,
S_CONTACT_TNTX,
S_ORG_EXT,
S_ORG_EXT ORGEXT_REF,
S_ADDR_PER,
S_ASSET a,
S_PROD_INT,
S_ASSET a2,
S_ASSET a3,
UPL_CLIENT_TYPES ct,
(select /*+ parallel */ o.contact_id, o.accnt_id
from S_ORDER o, S_ORDER_XM oxm
where o.row_id = oxm.par_row_id
and trunc(oxm.X_BUSINESS_DATE - (UTC_OFFSET/24)) = trunc(p_business_date)
group by o.contact_id, o.accnt_id) oxm2
WHERE S_CONTACT.ROW_ID = S_CONTACT_X.PAR_ROW_ID
AND S_CONTACT_X.ROW_ID = S_CONTACT_XM.PAR_ROW_ID (+)
AND (S_ORG_EXT.ROW_ID = S_CONTACT.PR_DEPT_OU_ID
OR S_ORG_EXT.ROW_ID = oxm2.accnt_id
OR S_ORG_EXT.ROW_ID = S_CONTACT_XM.attrib_05)
AND ORGEXT_REF.ROW_ID(+) = REFERRER.PR_DEPT_OU_ID
AND S_CONTACT.CON_ASST_PER_ID = Consultant.ROW_ID
AND S_ORG_EXT.X_DIRECTOR_ID = ProgramDirector.ROW_ID (+)
AND S_CONTACT.CREATED_BY = CallTaker.ROW_ID
AND S_CONTACT.ROW_ID = a.PR_CON_ID (+)
AND S_CONTACT.PR_PER_ADDR_ID = S_ADDR_PER.ROW_ID (+)
AND S_CONTACT_TNTX.PAR_ROW_ID (+) = S_CONTACT.ROW_ID
AND REFERRER.ROW_ID(+) = S_CONTACT_TNTX.REFERRED_BY_ID
AND a.PROD_ID = S_PROD_INT.ROW_ID (+)
AND O.CONTACT_ID (+) = S_CONTACT.ROW_ID
AND a.STATUS_CD (+) = 'Active'
AND a.TYPE_CD (+) ='Program'
AND S_CONTACT.ROW_ID = a2.PR_CON_ID (+)
AND a2.STATUS_CD (+) = 'Active'
AND a2.TYPE_CD (+) = 'Lifecycle'
AND a3.PR_CON_ID(+) = S_CONTACT.ROW_ID
AND a3.STATUS_CD (+) = 'Active'
AND a3.TYPE_CD (+) = 'HealthSheet'
AND S_CONTACT.X_JC_ACNT_NUM = ct.CLIENT_NUMBER (+)
--AND S_ORG_EXT.LOC NOT LIKE 'F%'
AND S_ORG_EXT.ACCNT_TYPE_CD NOT IN 'Division'
--AND S_ORG_EXT.Loc in (select to_char(centreid) from UPL_LIVE_CENTRES where LIVE = 'Y')
AND (trunc(S_CONTACT.LAST_UPD - (UTC_OFFSET/24)) = trunc(p_business_date) or trunc(S_CONTACT_X.LAST_UPD - (UTC_OFFSET/24)) = trunc(p_business_date) OR (S_CONTACT_XM.X_CONSULTATION_DT = p_business_date) OR oxm2.CONTACT_ID IS NOT NULL)
AND S_CONTACT.last_upd_by not in ('1-14WD')
AND oxm2.CONTACT_ID (+) = o.CONTACT_ID
AND S_ORG_EXT.LOC <> 'CW_846'
AND (a.pr_accnt_id in (select row_id from S_ORG_EXT where S_ORG_EXT.LOC IN (Select CentreID from UPL_Live_Centres where BATCHID = p_batch_id)) or a.pr_accnt_id is null)
AND (a2.pr_accnt_id in (select row_id from S_ORG_EXT where S_ORG_EXT.LOC IN (Select CentreID from UPL_Live_Centres where BATCHID = p_batch_id)) or a2.pr_accnt_id is null)
AND (a3.pr_accnt_id in (select row_id from S_ORG_EXT where S_ORG_EXT.LOC IN (Select CentreID from UPL_Live_Centres where BATCHID = p_batch_id)) or a3.pr_accnt_id is null));
rollback;
END;
-------------------------------------------------------------------------------------------------- -
Need help for the sql statement !!!!!
hi all,
i need a sql statement for a query, how can i get the result from the rownum between 100 and 150?
plz helpuse a scrollable statement:
PreparedStatement stat = Connection.prepareStement("select * from blah", ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stat.executeQuery();
rs.absolute(100);
while (rs.next()) {
String something = rs.get(1);
Look into the JDK API reference for ResultSet to get an expalantion of scrollable statements. -
Help for Pl/SQL Logic & Syntax used
Hi, in Ivan Bayross' book, following example is given illustrating use of triggers.
Create trigger audit_trail
After update or delete on customer
for each row
DECLARE
oper VARCHAR(20);
BEGIN
If updating then
oper :='UPDATE';
End if;
If deleting then
oper :='DELETE';
End if;
Insert into audit_cust
Values(*:OLD.CUST_NO* , *:OLD.FNAME* );
END;
Questions :*
1. Why : symbol is used in insert query above? Viz. :OLD.CUST_NO
what does it indicate ?? ALso, what does . ( dot operator) indicates?
OLD is not table name.
2. In the program above what does this line mean??
If deleting then
oper :='DELETE';
End if;
We are just assigning value 'DELETE' to oper variable ?? or something else??Hi,
So, still struggling on Ivan's book, eh ;-) ?
1. :OLD and :NEW means you can refer to the old and new column values.
They are only usable in triggers.
So, if you're updating column X from 1 to 2, the value of :OLD.X = 1 and :NEW.X = 2 in your trigger only.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/triggers.htm#CNCPT118
http://www.oracle.com/pls/db102/search?word=TRIGGER&partno=
We are just assigning value 'DELETE' to oper variable ?? or something else??I guess the autor meant do do this:
Create trigger audit_trail
After update or delete on customer
for each row
DECLARE
oper VARCHAR(20);
BEGIN
If updating then
oper :='UPDATE';
End if;
If deleting then
oper :='DELETE';
End if;
Insert into audit_cust
Values( :OLD.CUST_NO, : OLD.FNAME, oper );
END;He probably forgot to insert the oper variable in his audit table, -
Hi all
I am new to oracle.Can anybody suggest me the books,websites to practise procedure,cursor,triggers,function,packages.specially assignments on thishttp://www.oracle.com/pls/db112/portal.portal_db?selected=1&frame=#developer_essentials
http://asktom.oracle.com
http://www.sqlsnippets.com/en/home.html -
Help asked for a sql request - thanks
Hello,
I'm not a sql Guru... Who can help for this sql request ?
First I have this:
SELECT ADDINFO_ID, INFO, LANGUAGE_FK, ENGLISH_NAME
FROM V_ADDINFOS
WHERE LANGUAGE_FK = 'EN' (which is very simple...-)
But now complicated... I have to add this in the same request:
select sum(val) as nbrInfo
from(
select count(*) val from eccgis where addinfo1_fk = ADDINFO_ID
union all
select count(*) val from eccgis where addinfo2_fk = ADDINFO_ID
union all
select count(*) val from eccgis where addinfo3_fk = ADDINFO_ID
union all
select count(*) val from thirdgis where addinfo1_fk = ADDINFO_ID
union all
select count(*) val from thirdgis where addinfo2_fk = ADDINFO_ID
In other words, for each row of the first select, I need to know how much it is linked in the tables eccgis and thirdgis...
Hope is is clear... -)
Thank you very very much,
MichelHi, Michel,
Almost anywhere that SQL allows an expression (such as a column name, literal or function call) it also allows a scalar sub-query, a SELECT statement based on any table (or tables) that returns one column and (at most) one row. Like other sub-queries, scalar sub-queries can be corellated to the main query.
To get the grand total you want on each row of your output:
SELECT ADDINFO_ID, INFO, LANGUAGE_FK, ENGLISH_NAME
, (select count(*) from eccgis where addinfo1_fk = ADDINFO_ID)
+ (select count(*) from eccgis where addinfo2_fk = ADDINFO_ID)
+ (select count(*) from eccgis where addinfo3_fk = ADDINFO_ID)
+ (select count(*) from thirdgis where addinfo1_fk = ADDINFO_ID)
+ (select count(*) from thirdgis where addinfo2_fk = ADDINFO_ID)
AS nrbInfo
FROM V_ADDINFOS
WHERE LANGUAGE_FK = 'EN';VERY IMPORTANT: Each sub-query must be in parentheses. You'll get a run-time error if any scalar sub-query returns more than one row. (Returning no rows is okay: the value will be NULL).
By the way, this looks like a bad table design. If each row in eccgis or thirdgis can be associated with more than one foreign key, they should be kept in a separate table. That's the standard way to handle many-to-many relationships. -
Hi guys,
I would like to know, how can I stop an anonymus pl/sql block (what is the command, what rights do I need in order to execute the command, etc). We use TOAD for PL/SQL programming and I know that administrators can stop processes from Enterprise Manager.
But yesterday I started a block which is in an infinite loop and the administrator is on holiday, and the table is growing bigger and bigger and the tablespace will be full sooner or later.
So help pls.
Thanks,
GaborTOAD has a cancel button for SQL commands, but for PL/SQL blocks it doesn't show up.
The tablespace will fill up certainlly for monday, but it happened me for several times that I wanted to stop a pl/sql script and each time I had to call the administration. This is what I don't want to do all the time, so it would be nice to have the right to stop my bad PL/SQL scripts myself.
A different question whether the administrator will grant me those rights to stop a PL/SQL script. But maybe , because we work on a developer server, not on the real one.
Regards,
Gabor -
Why named parameter can't be used multiple times in PL/SQL block in JDBC
with the following PL/SQL block, when I run int in JDBC, I get an error,
it says, The number of parameter names does not match the number of registered parameters.
if all named parameters are used only once, then my program works fine.
My old program uses Oracle Forms to run the attached PL/SQL block correctly, I just want to run them in JDBC without more efforts, I don't want to rewrite all PL/SQL blocks.
Does oracle driver support this case? why the PL/SQL block can work in Oracle Forms but failed in JDBC?
Can we have an another solutions to avoid rewriting the PL/SQL block to stored procedure?
if I use following SQL:
BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;
, Using java program:
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
in the coding, only "q" registered, I got:
java.sql.SQLException: The number of parameter names does not match the number of registered praremeters at oracle.jdbc.driver.OracleSql.setNamedParameters(OracleSql.java:314) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10096) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:28)
now, tried to register 3 indexes, changed fragments are below.
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :q := 'X'; else :q := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(1, Types.VARCHAR); stmt.registerOutParameter(2, Types.VARCHAR); stmt.registerOutParameter(3, Types.VARCHAR); stmt.setString(1, "A"); stmt.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
now error changed to:
java.sql.SQLException: ORA-01006: bind variable does not exist at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:457) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:400) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:926) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:476) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:200) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:543) at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:208) at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:1416) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1757) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4372) at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:4595) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10100) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:26)
, now tried register only 1 position like below,
CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(1, Types.VARCHAR); stmt.setString(1, "A"); stmt.execute();
, it says:
java.sql.SQLException: Missing IN or OUT parameter at index:: 2 at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:2177) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4356) at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:4595) at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:10100) at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:5693) at RunPLSQLBlock.main(RunPLSQLBlock.java:26)
, now let try a OK case, which use all named parameters only once. coding like below, SQL and Java listed below.
BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; END;
import java.sql.*; public class RunPLSQLBlock { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL = "BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; END;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.registerOutParameter("r", Types.VARCHAR); stmt.registerOutParameter("s", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); System.out.println("Q :" + stmt.getString("q")); System.out.println("R :" + stmt.getString("r")); System.out.println("S :" + stmt.getString("s")); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the case give us the following output:
Q :A R :null S :Y
2nd part, I also tried another scheme, to use 'execute immediate', test code attached below, it also have errors.
begin execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out :q, out :r; end;
, Java Code:
import java.sql.*; public class RunDynamicSQL { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL ="begin execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out :q, out :r; end;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter("q", Types.VARCHAR); stmt.registerOutParameter("r", Types.VARCHAR); stmt.setString("q", "A"); stmt.execute(); System.out.println("Q :" + stmt.getString("q")); System.out.println("R :" + stmt.getString("r")); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the output is, we can find when parameter 'q' is IN OUT mode, we can't get its final value:
Q :null R :Z
, now I tried my workaround, it works fine by using a temporary variable, now my named parameter is split to 2 roles, one is for IN, another is for OUT, now I can get final out value.
declare q clob; r clob; begin q := ?; r := ?; execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r; ? := q; ? := r; end;
, my test java code,
import java.sql.*; public class RunDynamicSQL { public static void main(String s[]) throws SQLException { String URL = "jdbc:oracle:thin:@192.168.11.199:1521:TIBSTEST"; Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = (Connection) DriverManager.getConnection(URL, "FBP1DEV", "FBP1DEV"); String SQL ="declare q clob;r clob; begin q := ?; r := ?; execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r; ? := q; ? := r; end;"; CallableStatement stmt = con.prepareCall(SQL); stmt.registerOutParameter(3, Types.VARCHAR); stmt.registerOutParameter(4, Types.VARCHAR); stmt.setString(1, "A"); stmt.setString(2, "A"); stmt.execute(); System.out.println("Q :" + stmt.getString(3)); System.out.println("R :" + stmt.getString(4)); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.close(); } } } }
, the output is expected,
Q :Y R :Z
Database:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
JDBC Driver, extracted from ojdbc6_g.jar/META-INF/MANIFEST.MF :
Created-By: 1.5.0_30-b03 (Sun Microsystems Inc.)
Implementation-Vendor: Oracle Corporation
Implementation-Title: JDBC debug
Implementation-Version: 11.2.0.3.0
Repository-Id: JAVAVM_11.2.0.3.0_LINUX_110823
Specification-Vendor: Sun Microsystems Inc.
Specification-Title: JDBC
Specification-Version: 4.0
Main-Class: oracle.jdbc.OracleDriver
JDK:
java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)
Edited by: jamxval on 2013-3-22 2:01PM (UTC+08:00), Give full test java program and SQL, added environment/API level; Attached another problem.
Edited by: jamxval on 2013-3-26 17:57 (UTC +08), Adjust code styleHi, thanks for your response, now I see, the named parameter is for stored procedure only, for PL/SQL block we name it placeholder name.
After cast my java.sql.CallableStatement to oracle.jdbc.OracleCallableStatement, I can find setStringAtName,
now, I have only one question:I can't find corresponding methods for registerOutputParameter, how we fetch output value?
I tried to callableStatement.getString("q"); it reports errors, but there are no ordinal binding in my source code, does placeholder names doesn't support OUT mode?
Java:
CallableStatement stmt = con.prepareCall("BEGIN if :q is null then :r := 'X'; else :s := 'Y'; end if; END;");
oracle.jdbc.OracleCallableStatement call = (oracle.jdbc.OracleCallableStatement) stmt;
call.registerOutParameter("q", Types.VARCHAR);
call.registerOutParameter("r", Types.VARCHAR);
call.registerOutParameter("s", Types.VARCHAR);
call.setStringAtName("q", "A");
call.setStringAtName("r", "A");
call.setStringAtName("s", "A");
call.execute();
System.out.println("Q :" + call.getString("q"));
</Java>
<output>
java.sql.SQLException: 不允许的操作: Ordinal binding and Named binding cannot be combined!
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.OracleCallableStatement.getString(OracleCallableStatement.java:2834)
at RunPLSQLBlock.main(RunPLSQLBlock.java:33)
</output>by the way, in my below-mentioned SQL 'problematic', when my code uses 'execute immediate' and use placeholder names in IN OUT mode, we always get NULL value (i.e. ':q'), but we can get final value of ':r' when ':r' is OUT mode only; now I get a workaround attached in below-mentioned 'my workaround' block, which split the IN OUT roles to 2 parts, it can work now;
It seems that the difference between 'problematic' and 'my workaround' imply that there are something work unexpectedly when the driver process the placeholder names, because 'my workaround' and ':r in problematic case' make sure the 'execute immediate' returned output values correctly, unluckly driver layer can't get return values.
<SQL name = 'problematic'>
begin
execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;'
using in out :q, out :r;
end;
</SQL>
<SQL name='my workaround'>
declare
q clob;
r clob;
begin
q := ?;
r := ?;
execute immediate 'begin if :q is null then :q := ''X''; else :q := ''Y''; :r := ''Z''; end if; end;' using in out q, out r;
? := q;
? := r;
end;Edited by: EJP on 26/03/2013 14:14 -
How to test for différent Select into a single PL/SQL block ?
Hi,
I am relatively new to PL/SQL and I am trying to do multiple selects int a single PL/SQL block. I am confronted to the fact that if a single select returns no data, I have to go to the WHEN DATA_NOT_FOUND exception.
Or, I would like to test for different selects.
In an authentification script, I am searching in a table for a USER ID (USERID) and an application ID, to check if a user is registered under this USERID for this APPLICATION.
There are different possibilities : 4 possibilities :
- USERID Existing or not Existing and
- Aplication ID found or not found for this particular USERID.
I would like to test for thes 4 possibilities to get the status of this partiular user regardin this application.
The problem is that if one select returns no row, I go to the exception data not found.
In the example below you see that if no row returned, go to the exception
DECLARE
P_USERID VARCHAR2(400) DEFAULT NULL;
P_APPLICATION_ID NUMBER DEFAULT NULL;
P_REGISTERED VARCHAR2(400) DEFAULT NULL;
BEGIN
SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
WHERE USERID = :P39_USERID AND APPLICATION_ID = :APP_ID ;
:P39_TYPE_UTILISATEUR := 'USER_REGISTERED';
EXCEPTION
WHEN NO_DATA_FOUND THEN
:P39_TYPE_UTILISATEUR := 'USER_NOT_FOUND';
END;I would like to do first this statement :
SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
WHERE USERID = :P39_USERID Then to do this one if the user is found :
SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
WHERE USERID = :P39_USERID AND APPLICATION_ID = :APP_ID ;etc...
I basically don't want to go to the not found exception before having tested the 4 possibilities.
Do you have a suggestion ?
Thank you for your kind help !
ChristianSurely there are only 3 conditions to check?
1. The user exists and has that app
2. The user exists and doesn't have that app
3. The user doesn't exist
You could do this in one sql statement like:
with mimic_data_table as (select 1 userid, 1 appid from dual union all
select 1 userid, 2 appid from dual union all
select 2 userid, 1 appid from dual),
-- end of mimicking your table
params_table as (select :p_userid userid, :p_appid appid from dual)
select pt.userid,
pt.appid,
decode(min(case when dt.userid = pt.userid and dt.appid = pt.appid then 1
when dt.userid = pt.userid then 2
else 3
end), 1, 'User and app exist',
2, 'User exists but not for this app',
3, 'User doesn''t exist') user_app_check
from mimic_data_table dt,
params_table pt
where pt.userid = dt.userid (+)
group by pt.userid, pt.appid;
:p_userid = 1
:p_appid = 2
USERID APPID USER_APP_CHECK
1 2 User and app exist
:p_userid = 1
:p_appid = 3
USERID APPID USER_APP_CHECK
1 3 User exists but not for this app
:p_userid = 3
:p_appid = 2
USERID APPID USER_APP_CHECK
3 2 User doesn't exist -
My First while loop inside PL/SQL block not working , please help
Hi ,
I am new to PL/sql and struck at PL SQL blocks , please help to solve this .
declare
v_A number constant :=10 ;
j number constant := 3 ;
BEGIN
WHILE j < v_A
LOOP
DBMS_OUTPUT.PUT_LINE('Hai');
END LOOP;
END;
please help as how to resolve this .
Thanks in advance .btw it's a useful habit to use indentation to highlight the block structure. Also it's worth deciding what your convention will be for keywords (I use uppercase, lowercase is also fine as far as I'm concerned but I've set up my editor to uppercase them) and variables, database object names etc (I use lowercase), e.g:
DECLARE
v_a CONSTANT PLS_INTEGER := 10;
j CONSTANT PLS_INTEGER := 3;
i PLS_INTEGER := j;
BEGIN
WHILE i <= v_a LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i +1;
END LOOP;
END;or perhapsdeclare
v_a constant pls_integer := 10;
j constant pls_integer := 3;
i pls_integer := j;
begin
while i <= v_a loop
dbms_output.put_line(i);
i := i +1;
end loop;
end;When I see "declare" and "BEGIN" in the same block of code I worry about the standard of code I'm going to see... -
PL SQL block - Check for empty file
Hello,
I need help in writing pl sql code to check a file to verify if it has 0 records (file size = zero kb.) In a preceding pl sql block, I am performing a SELECT on data and writing it to a file. If that file is empty/has no records, then I would like to stop the process from continuing on to my next pl sql block which performs an update function.
Summary:
1) Create file from SELECT
2) Check file for zero data, if true, trigger error, if false, continue to next pl sql block.
3) Run update on records if data exists in the file.
Thanks in advance!Thanks John,
You've been of great help so far and a really appreciate it. I'm so close to getting this, I just need help with how to create an error when the file shows no data. I will be running this as an Oracle Apps Concurrent request. I'd like for the job to end in error when no data exists for the file. In unix, I can enter "EXIT 1" and it signals to the concurrent manager to put end the job with an error status. How can I do something similar using pl sql? Here is my code so far, with the missing piece. Thanks!
DECLARE
vFile UTL_FILE.FILE_TYPE;
vrecs BOOLEAN := FALSE;
vnodata EXCEPTION;
BEGIN
vFile := UTL_FILE.FOPEN('/devlop, 'norecs.txt', 'w', 32767);
FOR x IN (
SELECT
node_name AS txt
FROM
applsys.fnd_nodes
WHERE
node_name = 'blahblahblah'
LOOP
vrecs := TRUE;
UTL_FILE.PUT_LINE (vFile, x.txt);
END LOOP;
UTL_FILE.FCLOSE(vFile);
IF NOT vrecs THEN
RAISE vnodata;
END IF;
EXCEPTION
WHEN vnodata THEN
*<what can I put here to cause the pl sql block to error???>*
END;
/ -
HTML not working in PL/SQL block..Help me ASAP
declare
l_col VARCHAR2(30) :=to_number(to_char(to_date('01-feb-2011','dd-mon-yyyy'),'dd'));
CURSOR name_cur IS
select name
from od_shift_schedule
where year=2011
and (month)=('Feb')
and decode(l_col,1,"01",2,"02",3,"03",4,"04",5,"05",6,"06",7,
"07",8,"08",9,"09",10,"10",11,"11",12,"12",13,"13",14,"14",15,"15",16,"16",17,"17",18,"18",19,"19",20,"20",
21,"21",22,"22",23,"23",24,"24",25,"25",26,"26",
27,"27",28,"28",29,"29",30,"30",31,"31")='W';
BEGIN
DELETE FROM nam;
commit;
FOR i IN name_cur
LOOP
dbms_output.put_line(i.name);
htp.p('<b>Employee '||i.name||' has been ticked.
</b><br/>');
EXECUTE IMMEDIATE 'insert into nam(name) values('''||i.name||''')';
commit;
END LOOP;
end;Kindly help me with this
If i'm wrong here kindly help me that how can i place a display messageRe: HTML not working in PL/SQL block..Help me ASAP
Using the community discussion forums for urgent issues is rude and a violation of the terms and conditions.
http://www.oracle.com/html/terms.html
>
4. Use of Community Services
Community Services are provided as a convenience to users and Oracle is not obligated to provide any technical support for, or participate in, Community Services. While Community Services may include information regarding Oracle products and services, including information from Oracle employees, they are not an official customer support channel for Oracle.
You may use Community Services subject to the following: (a) Community Services may be used solely for your personal, informational, noncommercial purposes; (b) Content provided on or through Community Services may not be redistributed; and (c) personal data about other users may not be stored or collected except where expressly authorized by Oracle
>
Also please read the FAQ on how to ask questions.
SQL and PL/SQL FAQ
>
2) Thread Subject line
Give your thread a meaningful subject, not just "help please", "Query help" or "SQL". This is the SQL and PL/SQL forum. We know your question is going to be about those things, make it meaningful to the type of question so that people with the right sort of knowledge can pick it up and those without can ignore it. Never, EVER, mark your subject as "URGENT" or "ASAP"; this forum is manned by volunteers giving their own time to help and your question is never urgent or more important than their own work or than other people's questions. It may be urgent to you, but that's not forum members issue. -
Help in solving this pl/sql block
Hi
Could some one help me in solving my problem
i want some data to be extracted by a sql its not fetching it so i prefered to write a pl/sql block for it ...
the block is as follows
begin
cursor opunit is
select code from fmg_operating_units;
cursor pak_code is --- those are the 3 codes which i require
select 'BNL' from dual
union select 'HNA' from dual
union select 'HNL' from dual;
cursor data1(opunit,pak_code) is
select mas.name ,
cl.id ,
opup.oun_code ,
fmg_phone_no(mas.id),
clpk.pak_code ,
clpk.id
from fmg_op_unit_positions opup,
fmg_clients cl,
fmg_client_paks clpk,
fmg_masters mas,
fmg_policies po,
fmg_policy_items pi
where mas.id=cl.mas_id
and cl.id=clpk.cli_id
and clpk.oup_id=opup.id
and opup.oun_code = opunit
and clpk.id=po.ctp_id
and po.id=pi.pol_id
and pi.current_status='AC'
and clpk.pak_code = pak_code;
loop opunits
loop pak_code
open data1
fetch data1(opunit,pak_code) ;
end loop;
end loop;
could some one help me in extracting the data and put it on the CSV file ...
i would be very thank full to you if some one take some time to full fill this task..
thanks in advanceDeclare
cursor opunit is
select distinct code
from fmg_operating_units;
cursor pak_code is --- those are the 3 codes which i require
select 'BNL' codes from dual
union
select 'HNA' codes from dual
union
select 'HNL' codes from dual;
cursor data1(opunit,pak_code) is
select mas.name ,
cl.id ,
opup.oun_code ,
fmg_phone_no(mas.id),
clpk.pak_code ,
clpk.id
from fmg_op_unit_positions opup,
fmg_clients cl,
fmg_client_paks clpk,
fmg_masters mas,
fmg_policies po,
fmg_policy_items pi
where mas.id = cl.mas_id
and cl.id = clpk.cli_id
and clpk.oup_id = opup.id
and opup.oun_code = opunit
and clpk.id = po.ctp_id
and po.id = pi.pol_id
and pi.current_status= 'AC'
and clpk.pak_code = pak_code;
begin
FOR opunits IN opunit LOOP
FOR pak_codes IN pak_code LOOP
OPEN data1;
fetch data1(opunits.code,pak_codes.codes) ;
EXIT WHEN data1%NOTFOUND;
< Rest of your code here > -- You can insert processed data into a temp table &
-- extract data from that table afterwards via select statement
-- & saving the data in a .cvs file extension.
CLOSE data1;
END LOOP;
END LOOP;
<Some more code here if applicable>
EXCEPTION
<Exception handling code section here>
END; -
Why do i have to init a VARCHAR for a SELECT in a Pro*C PL/SQL block?
Hi,
i use PL/SQL Block in a Embedded C Programm and compile with the PRO*C Compiler. Oracle 10gR2.
When i Select .. Into a VARCHAR bind variable, i have to initialize the variable before, otherwise i get an ORA-1458.
Same problem with assignments to VARCHAR variables.
Question: why do i need to initialize the variable?
Tnx for your help!
The following test program shows my issue:
#include <stdio.h>
#include <string.h>
#include "oraca.h"
#include "sqlca.h"
#define USER "scott"
#define PASSWORD "tiger"
int main()
EXEC SQL BEGIN DECLARE SECTION;
char *db_user = USER;
char *db_passw = PASSWORD;
VARCHAR sysdate_str[64];
EXEC SQL END DECLARE SECTION;
EXEC SQL CONNECT :db_user identified by :db_passw;
/* this works */
sysdate_str.len = 1000; /* invalid length */
EXEC SQL SELECT
to_char( sysdate, 'dd.mm.yy hh24:mi:ss' )
into :sysdate_str
from DUAL
printf ("sqlca.sqlcode %d\n", sqlca.sqlcode);
/* following code does not work, sqlcode = - 1458 */
/* 01458, 00000, "invalid length inside variable character string" */
sysdate_str.len = 1000; /* invalid length */
EXEC SQL EXECUTE
BEGIN
select to_char( SYSDATE, 'dd.mm.yy hh24:mi:ss')
into :sysdate_str
from dual;
END;
END-EXEC;
printf ("sqlca.sqlcode %d\n", sqlca.sqlcode);
/* following code does not work, sqlcode = - 1458 */
/* 01458, 00000, "invalid length inside variable character string" */
sysdate_str.len = 1000; /* invalid length */
EXEC SQL EXECUTE
BEGIN
:sysdate_str := to_char( SYSDATE, 'dd.mm.yy hh24:mi:ss');
END;
END-EXEC;
printf ("sqlca.sqlcode %d\n", sqlca.sqlcode);
return(0);
Edited by: jjaeckel on May 5, 2010 8:37 PMjjaeckel wrote:
When i Select .. Into a VARCHAR bind variable, i have to initialize the variable before, otherwise i get an ORA-1458.A bind variable in a SQL is simply a place holder. The SQL engine has no idea what data type the value for that placeholder will be. When itself needs to return a value via that placeholder to the caller, it needs to know what the limits/size of the caller's variable is that will be receiving the value from it.
The way that the SQL engine knows what the data type and size are of a placeholder/bindvar, is by you the caller, telling it.. by binding the variable you will be using, to this placeholder.
This bind process "exposes" the data type and size of the variable that will be used for binding (sending/receiving data).
Maybe you are looking for
-
Hello, I have found a lot of discussion about the SQL Injection. Seems like it is very famous issue nowadays. I am currently doing some findings on the SQL injection and hopefully this thread may give some benefits to everyone. 1. has SQLIA been reso
-
Deadlock detected but lmd log not found
We've an Oracle 10g RAC database. The version number is: 10.2.0.3.0. In one application sometimes we get deadlock error. When we check the alert log we see: Global Enqueue Services Deadlock detected. More info in file /oracle/product/admin/WEBCREAL/b
-
Problem with labelfunction with checkbox itemrenderer
I have a DataGrid with a column that looks like this: <mx:DataGridColumn headerText="Buy online?" dataField="onlineshop" itemRenderer="mx.controls.CheckBox" rendererIsEditor="true" labelFunction="checkBoxLabel" editorDataField="selected" /> My label
-
Manipulate databases in Oracle 10g XE R2
Hi all, I need to create and manipulate databases in Oracle 10g XE R2 using perl DBI:1.607 please can someone help me with some documentation thank you in advance
-
Events in iCalendar & Outlook are duplicated; sometimes 10+ times!
Why are events in my iCalendar, and Outlook for Mac, being duplicated, sometimes 10 times; even after I delete the duplicated event? When I synch my iPhone and iPad with the Mac, the events are duplicated in those devices as well.