BOM Recursive logic
Hello All,
I need a logic for re-cursive call.I am drilling down the BOM components.Example as below.
If I have A as header with B as component and again B may have C as component again C may have D and E as components in it.
Now if I pass A i should find B,C,D,E,F.
Please suggest somebody some idea how to get this logic?
I am using the function module CS_BOM_EXPL_MAT_V2 to get the components of a BOM.
Regards
Mahesh
Hello Mahesh
I would assume that if you set IMPORTING parameter MEHRS ( Multi-level explosion ) = 'X' and do not restrict the multi-level explosion then you should get the entire hierarchy.
Regards
Uwe
Similar Messages
-
Hi,
In BOM recursiveness check, whether the system will consider the BOM usage into account?
As per the note 42891,
For reasons of performance, the system does not make any fine distinctions during the recursiveness check in the BOM explosion.
1. BOM items of a bill of material are treated as being assigned to all variants of a variant BOM or as being assigned to all configured materials of a configured bill of material.
2. The effectivity (date / parameter effectivity) is not taken into account.
3. The plant is not taken into account.
4. The usage is not taken into account.
Here the usage is not taken into account, what does it mean?
Explain please.
Thanks,
Suresh.Hello Suresh,
It means that during the recursive check , it does not check if it is a different plant or a usage . if a bom is created for Plant A and usage 3 , and you now try to create a bom for Plant B or usage 1, system will still raise an error and find it recursive.
Eg if you already have a BOM with
Header Material A
Component B
Usage 1
And now if you create a BOM with
Header Material B
Component A
Usage 5
It will be seen as recursive and you should receive an error.
Hope that helps
Regards
Amber -
Hi All,
Can any one guide me regarding the steps of OSS note 839879 - Trace 'BOM is recursive' i.e procedure to trace bom RECURSIVENESS.
Thanks in AdvHi ,
Note 681126 was useful.
In my scenario
Material.- A and B in plant X.....A and B are co-product for this plant and in BOM B is a component of A
Material- C and B in plant Y...C and B are not the co product for this plant and in BOM B is a component of C. Here for B it is asking for "recusrsive allowed".
When i remove tick "co-product" (in BOM) for item B in plant x, then for item B in plant Y it is not asking for recursiveness.
Material C is not in Plant X.
Low level code for A, B & C are asfollows
A-000
B-011
C-005
I am not able to understand why it is behaving this way.
Regards,
Satyajit -
Hi All,
What is recursiveness allowed in BOMsHi Anand,,
If the header BOM material same you are using as a component then BOM become Recursive.
If you create a recursive BOM, you must decide whether you want to allow recursiveness or delete the component that caused the recursiveness,
Two users create a material BOM at the same time. Each user enters the BOM header material entered by the other user as a component.
One user saves the BOM. When the second user tries to save the BOM, the system recognizes recursiveness and sets the recursive indicator. The second user sees an online message about the recursiveness.
Please refer this link also,
[BOM-Recursive|http://help.sap.com/search/highlightContent.jsp]
Regards,
R.Brahmankar -
Hi,
I have the code below that does recursive calls. The final expression evaluates to a boolean when the recursion ends. However, there is loop hole in the logic below, that I have recognized but couldn't resolve though.
private boolean isMoClassFoundInAnyDepthInThisBaseMim(String notFoundMo, ContainmentDef[] containmentRelDef){
for (ContainmentDef conDef : containmentRelDef){
ClassDef[] classDefs = conDef.getToClasses();
for (ClassDef csDef : classDefs){
boolean moFound = false;
if ( csDef != null){
moFound = (csDef.getMIM().getClass(notFoundMo)) != null;
if (moFound) return true;
else{
final ContainmentDef[] containmentRelDefForChild = csDef.getContainments();
if (!moFound || containmentRelDefForChild.length > 0)
return ( isMoClassFoundInAnyDepthInThisBaseMim(notFoundMo, containmentRelDefForChild) || false );
}//end of inner if
}//end of outer if
}//end of inner loop
}//end of outer loop
return false;
The code logic is..
I loop over an array of containments. For each of the containments, I get their children which are the classDefinitions. I check to see if the classDefinition, csDef, contains something that I wanted, if not, I recurse the call to check, if any of the classDef's children, which are containments again, has got what I wanted.
The logic fails, when one of the containments has no child. It basically exits the outer for loop and returns false which should not happen, as I still have other containments to check.
I have tweaked the code in different ways, however, I am exhausted of ideas.
I request your help here.
Thanks in Advance...Hey,
It's a bit weard... It's like you never read all objects. I rewrite your code a bit:
private boolean isMoClassFoundInAnyDepthInThisBaseMim(
final String notFoundMo, ContainmentDef[] containmentRelDef) {
boolean returnValue = false;
boolean moFound;
ClassDef[] classDefs;
ContainmentDef[] containmentRelDefForChild;
if (containmentRelDef != null){
for (ContainmentDef conDef : containmentRelDef) {
classDefs = conDef.getToClasses();
for (ClassDef csDef : classDefs) {
moFound = (csDef.getMIM().getClass(notFoundMo)) != null;
if (moFound){
returnValue = true;
}else{
containmentRelDefForChild = csDef.getContainments();
returnValue = isMoClassFoundInAnyDepthInThisBaseMim(notFoundMo, containmentRelDefForChild) || false;
return returnValue;
}But I think it's still weard code (Check the complete array, if it's false I return false, it means the parent is false to and his parent...) ==> so normally you have to quit the loop if one of the lines return false... (this isn't checked here, and I didn't find this check in your code to...)
Normally this code should ends normally, except if the method csDef.getContainments() return the parent object to... The problem is that I doesn't have this objects, and it's a bit work to create all your objects just to check this function... -
Hi All,
I have a peculiar requirement
Please find it below.
There is a Select Options for Material.
Based on the Material BOM Explosion should happen.
Now in the resultant set of Materials if the Material (in Select Options) is present and this is treated as Recursive.
For Ex:
s_matnr = 1
now when material 1 is exploded its giving
2 3 4 1
Hence in the above case since 1 is appearing in the exploded set it is treated as "Directly Recursive"
Now again when 2 is exploded
we get 5 6 7
and when 3 is exploded
we get 8 9 10
and so on so forth.
If in any hierarchy / level the material in s_matnr ( 1 ) is appearing then its "Indirectly recursive".
The Explosion will continue for all the resultant set of exploded materials.
Please give me some kind of clue about this.'
The report they want is to display all the Materials with Direct/Indirect Recursive.
Waiting eagerly for your Hints/Replies
Hope you all have understood the requirement.
Please revert for further clarification i shall articulate the requirement .
Thanks
SriCheck this wiki for recursive logic link:[http://wiki.sdn.sap.com/wiki/display/Snippets/InverseBOMExplosion-ABAP]
For sequential logic use function CSAP_MAT_BOM_READ instead of fm CS_WHERE_USED_MAT used in the above link. -
hi experts,
i need standard LDB's related to the tables of sd, mm and fi... can anyone help regarding this.....Ok so here you are, If you want to edit one go to SE36
LDB name
Logical database short text
50V
Delivery in process
AAV
Logical Database RV: Sales Documents
ABCLAIMLDB
Agency Business: Complaints Processing
ABS
ABAP Book: Customer and bookings
ACAC_ACE_LDBDS
Accrual Object Distribution Server Reporting Table
ACAC_ACE_LDBPS
Accrual Engine Posting Server Reporting Database
ACE_FILA_LDBDS
Accrual Object Distribution Server Reporting Table
ACE_FILA_LDBPS
Accrual Engine Posting Server Reporting Database
ACE_SOP_LDBDS
Stock Option Accounting Distribution Server LDB
ACE_SOP_LDBPS
Provisions for Awards: Posting Server LDB
ACEDS_003
Accrual Object Distribution Server Reporting Table
ACEPS_003
Accrual Engine Posting Server Reporting Database
ADA
Assets Database
AFI
Logical database for orders
AGENCYLDB
Agency Business: Logical Database
AKV
Logical Database RV: Sales Documents
ALV
Archiving Deliveries
ARV
Logical Database RV: Sales Documents
ASV
Request Screen for Summary Information
AUK
Settlement documents
AUW
Allocation Table
B1L
Transfer requirements by number
BAF
BAV-Data collector
BAM
Purchase Requisitions (General)
BANK
Logical Database for Table BNKA
BBM
Archiving of Purchase Requisitions
BC405_DIFF_NODES
Example of Different Node Types
BJF
Loans flow records with date restriction(YR
BKK
Base Planning Object
BKM
Purchase Requisitions per Account Assignment
BMM
Documents for Number
BPF
Treasury Business Partner
BRF
Document Database
BRM
Accounting Documents
BTF
Loan portfolios and flows
BTM
Process Order; Print
BUCHUNGSJOURNAL
LDB for Posting Journal
BUD
LDB For Loans Master Data, Conditions, Documents
C1F
Cash Budget Management
CCLDB_AENR
ECH: Change number with status information
CDC
Document structure
CEC
Equipment BOM
CEK
Cost Centers - Line Items
CFK
Data pool for SAP EIS
CIK
Cost Centers - Actual Data
CKA
Costing
CKC
Sales order BOM
CKM
Material master
CKQ
Material Selection for New Costing Solution
CKS
MiniApp. for the Calculator: Sales Order Data
CKS_WAO
MiniApp: Sales Order Items to be Processed
CKW
Costing run: Material Selection
CMC
Material BOM
CPK
Cost Centers - Plan Data
CRC
Work Centers
CRK
Cost Centers - Total
CRZ
Logical database for courses BC220/BC230
CSC
Standard BOM
CSR
Logical database for archiving BOMs
CTC
Functional location BOM
DBM
MRP Documents
DDF
CUSTOMER DATABASE
DPM
Planned Orders
DSF
Loan Debit Position
DVS
Logical database for archiving DMS data
DWF
Loan resubmission
EBM
Purchasing Activities per Requirement Tracking No.
ECM
Purchasing Documents per Material Class
EHS_OH001
Logical Database for Occupational Health
EKM
Purchasing Documents per Account Assignment
ELM
Purchasing Documents per Vendor
EMM
Purchasing Documents for Material
ENM
Purchasing Documents per Document Number
EQI
Logical Database (Equipment)
ERM
Archiving of Purchasing Documents
ESM
Purchasing Documents per Collective Number
EWM
Purchasing Documents per Supplying Plant
F1S
BC: Planned flights, flights and bookings
FDF
Cash management and forecast
FDK
IS-U/FERC: Drill down to line items and paths
FEF
Cash Management - Memo Records
FILA
Lease Accounting
FMF
Funds Management
FPMF
LDB, reads FPAYH and FPAYP
FRF
Drill-down Selection Screen
FSF
Cash Management Totals Records
FTI_BW_CFM_VALUES
Market Values and Simulated Values in Pos. Mgmt
FTI_LO_PERIODS
Loan/CML Period Evaluations
FTI_LO_POSITIONS
Loan /CML Positions
FTI_SWAP_POSITION
Swap Positions
FTI_TR_CASH_FLOWS
Treasury Payment Information
FTI_TR_PERIODS
Treasury: Period-Based Evaluations
FTI_TR_PL_CF
Treasury: Revenue and Cash Flow Reporting
FTI_TR_POSITIONS
Treasury Positions
FTLM_DB01
Limit Management
FUK
IS-U/FERC: Drill back from document line items
G1S
text
GLG
FI-SL Totals and Line Items
GLU3
Flexible G/L
I1L
Inventory data for storage bin
I2L
Warehouse quants for storage bin
I3L
Inventory documents
IBF
Real Estate Logical Database (Lease-Out)
IDF
Real Estate Logical Database
IDFPLUS
Real Estate Plus Logical Database
IFM
Purchasing Info Records: General
ILM
Archiving Purchasing Info Records
IMA
Logical database for investment programs
IMC
IM Summarization (not usable operationally)
IMM
Inventory documents for material
IMR
Approp. requests (not operationally functional)
IMT
Approp. requests (not operationally functional)
INM
Inventory documents
IOC
Shop floor control - order info system
IPM_ACE_LDBDS
Accrual Object Distribution Server Reporting Table
IPM_ACE_LDBPS
Accrual Engine Posting Server Reporting Database
IRM
Reorganization of inventory documents
J5F
Logical Database for new Nota Fiscal Database
K1V
Generating Conditions
KDF
Vendor Database
KIV
Customer Material Information
KKF
Balance Audit Trail of Open Items
KLF
Historical Balance Audit Trail
KMV
SD Documents for Credit Limit
KOV
Selection of Condition Records
L1L
Evaluation Whse Documents
L1M
Stock movements for material
LMM
Stock Movements for Material
LNM
Stock movements
LO_CHANGE_MNMT
Logical database for engineering change management
MAF
Dataset for Dunning Notices
MDF
Logical Database for Master Data Selection
MEPOLDB
Logical Database/Selection of Purch. Order Tables
MIV
BC: Planned flights, flights and bookings
MMIMRKPFRESB
Selection from Reservations
MRM
Reorganization of material documents
MSM
Material master
NOTIF
LDB for Basic Notifications
NOTIFICATIONS
NTI
Logical database object networking
ODC
Shop floor control - orders per MRP controller
ODK
Orders
OFC
Shop floor control - orders per prod.scheduler
OHC
Shop floor control - orders by numbers
OPC
Shop floor control - orders by material
PAK
CO-PA Segment Level and Line Items
PAP
Applicant master data
PCH
Personnel Planning
PGQ
QM: Specs and Results of the Quality Inspection
PMI
Structure database (plant maintenance)
PNI
PM Planning Database
PNM
Planning database
PNM_OLD
Planning Database
PNP
HR Master Data
PNPCE
HR Master Data (Incl. Concurrent Employment)
POH
Production orders database - header
PSJ
Project system
PTRVP
Travel Management
PYF
Database for Payment Medium Print Programs
QAM
Inspection Catalogs: Selected Sets
QAQ
Inspection Catalogs: Selected Sets
QCM
Inspection Catalogs: Codes
QCQ
Inspection Catalogs: Codes
QMI
Logical database (PM notifications)
QMQ
Inspection Characteristics
QNQ
Quality Notifications
QTQ
Logical database for inspection methods
QUERYTESTLDB
Test LDB for InfoSet Query
R0L
Archive selection: Transfer orders (MM-WM)
R1L
Archive selection: Transfer requirements (MM-WM)
R2L
Archive Selection: Posting Change Notices (MM-WM)
R3L
Archive selection: Inventory documents (MM-WM)
R4L
Archive selection: Inventory histories (MM-WM)
RBL
Archiving of transfer requests
REAO
Real Estate: Logical Database for Architecture
REBD
Logical Database for Real Estate Objects
REBP
Logical Database via Partner (Real Estate)
RECN
Real Estate: Selection by Contracts
RECONTRACT
RE Logical Database: (General) Contract
RHL
Archiving of inventory history
RIL
Archiving of inventory documents
RKM
Reservations for Account Assignment
RLI
Logical Database Reference Location
RMM
Reservations for material
RNM
Reservations
RTL
Archiving of transfer orders
RUL
Archiving of Posting Change Notices
S1L
Stock by storage bins
S1L_OLD
Stock by Storage Bins
S2L
Warehouse quant for material
S3L
Stocks
SAK
Completely Reversed Allocation Documents
SD_KUSTA
Logical Database for Sales Summary
SD_ORDER
Logical database for inquiries, contracts
SD_SALES_DOCUMENT
Logical database for inquiries, contracts
SDF
G/L Account Database
SMI
Serial Number Management
T1L
Transfer orders by number
T1L_OLD
Transfer Orders by Number
T2L
Transfer orders for material
T3L
Transfer orders for storage type
T4L
Transfer order for TO printing
T5L
Transfer orders for reference number
TAF
Treasury
TIF
Treasury Information System
TPI
Functional Location Logical Database
U1S
User master reorganization: Password changes
U2S
User master reorganization: Password changes
U3S
User master reorganization: Password changes
U4S
User master reorganization: Password changes
UKM_BUPA
SAP Credit Management: Business Partner
V12L
Pricing Report
VAV
Logical Database RV: Sales Documents
VC1
List of Sales Activities
VC2
Generate Address List
VDF
Customer Database with View of Document Index
VFV
Logical Database RV: Billing Documents
VLV
Logical Database For Deliveries
VVAV
Logical Database RV: Sales Documents
VXV
SD: Billing Document - Export
WAF
Securities position plus additional master data
WOI
Maintenance Item
WPI
Maintenance plans
WTF
Securities positions and flows
WTY
WTY LD
WUF
Sec.-Determ.master data for positions
I hope this will delh -
Error Msg while BOM creation - Maximum low-level code 999 reached
Dear Expert,
After uploading the BOM (T-code: CS01) of material XXXXXXX in XXXX plant, error message through express message is coming regarding maximum low-level code 999 and the BOM is automatically getting deleted.
Error Info... Maximum low-level code 999 reached
Thanks & Rgds,
DipenIs by any chance this BOM recursive?
If so, you need to allow recursiveness specifically. -
Service procuremnt:gate pass issue
Hi,
we want to send the motor for rewinding outside the company.
as the repairing charges will be confirmed by vendor only when the motor is opened and checked by vendor at vendor site. so we need to send the motor with gate pass to vendor and after the check we wiil make po with respect to given quotation.
how sap system can issue and print the gate pass.
how we can check the report like moter sent ,motor received and the balance motor at vendor.
regards
ramanHi,
it is possible through new development only,
here is one possible solution,
maintain the split valuation for the material with different valuation types as damaged & reapaired,
create one BOM (recursive allowed ) indicator,
maintain one info record with the sub contracting vendor,
1.create one one new screen for gate pass entry with the input options of vendor,material no,quantity,valuation type and date,
if required print the gate pass with above details,
2. create one Z table to store the all above data
3. create one new movement type with replica of 541.
4.restrict the new movement type for MIGO transaction only
5.impliment the BADI MB_MIGO_BADI to get the new tab for MIGO screen with the point 1 input details,
(logic as new tab shuold only reflect for the new mvt )
6.if the user enters the point 1 details in the new tab of MIGO transaction ,system need to check the customised table ,and allow the posting after the validation only
7.at the time of MIGO with new mvt type enter the material with batch.
8. now the material issued to the sub contractor with valuation type as a 'damaged',
9.create one sub contracting PO for the material with bacth 'repaired'
10. as per the normal , receive the goods against PO.
at any point of time you can trace the material with batch wise.
hope this is helpful
regards
chenna -
How do I delete cascade with a PL/SQL procedure?
This script will create a PL/SQL procedure that deletes cascade. This is a post to contribute to the Oracle community. Take the code as is and test it before you use it in production. Make sure this is what you want.
Procedure Delete Cascade (prc_delete_cascade)
Description
=============
The principle is very simple. The procedure uses a table called TO_BE_DELETED to keep a list of records to be deleted. This
table keeps the table name and the rowid of those records that need to be deleted. The procedure also uses a function called
DELETE_BOTT_ROW which takes one record of the table and tries to delete it. If the deletion fails with a foreign key constraint
violation, the function parses the SQL error message (SQLERRM) to get the name of the constraint. With the name of the constraint,
the function finds the name of the child table, all the child records that have references to the parent table primary or unique key,
and the parent key primary or unique key column name. Once the child records of the failed delete are identified, the function takes their table name and rowids
and records them into the TO_BE_DELETED table by inserting records of their table name and their rowids. Al the records inserted also contain the level (which
is 1 for the original records, 2 for child records, 3 for granchild records, etc.) and the sequence number of the order in wich they
are recorded. This way, when the function picks up a record to be deleted, it takes the one with the highest level and the highest
inserted sequence, or the "bottom" record. Once all the child records of the failed delete are appended to the TO_BE_DELETED table, it calls itself
recursevely, and the function takes the record at the "bottom" of the table and tries to delete it. If it succeeds, it calls
itself recursevely to delete the next record. If it fails, it goes and finds the child records as described before and once they are
inserted into the TO_BE_DELETED table, it calls itself again recursevely to try to delete again the "bottom" record. All records
that are successfully deleted are flagged as deleted usig the flag_del column so they are not pickt up again. Once all the (parent,
child, grandchild, etc.) records are deleted, the procedure ends without commiting, giving the option to the user to commit or
rollback deletions. The table TO_BE_DELETED is, at the end of the procedure, a list of all the records that were deleted, including their table names
and the order in with they were deleted. The user then can review its content and decide to commit or rollback.
Restrictions
============
1. Single tables only. The procedure only takes one table name and a WHERE clause to identified the records to be deleted.
2. Single columns only. Ther procedure only works with single-column primary, unique and foreign key constraints.
3. Single schema only.
4. Unpredictable results with circular references.
drop table to_be_deleted purge;
create table to_be_deleted
(tname varchar2(30) -- table name
,rid rowid -- rowid
,lvl number -- level: 1=parent, 2=child, 3=grandchild, etc.
,seq_ins number -- sequence order of record inserted
,flg_del char -- flag deleted: Y=record deleted
,seq_del number -- global order of record deletion
set serveroutput on size 1000000
create or replace procedure prc_delete_cascade
(p_tname varchar2 -- table name
,p_where varchar2 -- where clause identifying records to be cascade deleted
is
dummy char;
v_sqlcode number;
v_sqlerrm varchar2(32767);
v_param_val integer := 0;
v_sql varchar2(4000);
v_ret_cde number;
e_bad_params exception;
v_iter number;
v_plvl number;
v_seq_del number;
v_max_iter number := 1000000000;
function delete_bott_row
return number
is
v_sql varchar2(4000);
v_ptname varchar2(30); -- parent table name
v_ppkname varchar2(30); -- parent primary key constraint name
v_ppkcname varchar2(30); -- parnet primary key column name
v_prowid rowid;
v_crowid rowid;
v_ctname varchar2(30); -- child table name
v_cfkname varchar2(30); -- child foreign key constraint name
v_cfkcname varchar2(30); -- child foreign key column name
v_ins number;
v_seq_ins number;
v_sqlerrm varchar2(4000);
v_sqlcode number;
e_const_viol exception;
pragma exception_init(e_const_viol, -2292);
e_max_iter_reached exception;
begin
v_iter := v_iter + 1;
if v_iter >= v_max_iter then
raise e_max_iter_reached;
end if;
dbms_output.put_line('- Iter '||to_char(v_iter));
dbms_output.put_line('----------');
dbms_output.put_line('- Starting function delete_bott_row');
v_sql := 'select tname, rid, lvl, seq_ins from (select * from to_be_deleted where flg_del = ''N'' order by lvl desc, seq_ins desc) where rownum=1';
-- dbms_output.put_line('- SQL: '||v_sql);
execute immediate v_sql into v_ptname, v_prowid, v_plvl, v_seq_ins;
dbms_output.put_line('- Selected row: table name: '||v_ptname||', level: '||v_plvl||', seq: '||v_seq_ins);
v_sql := 'delete from '||v_ptname||' where rowid='''||v_prowid||'''';
dbms_output.put_line('- SQL: '||v_sql);
execute immediate v_sql;
dbms_output.put_line('- Row deleted !!!');
v_ret_cde := 1;
v_seq_del := v_seq_del + 1;
dbms_output.put_line('- Mark the row deleted');
v_sql := 'update to_be_deleted set flg_del = ''Y'', seq_del = '||to_char(v_seq_del)||' where tname='''||v_ptname||''' and rid='''||v_prowid||'''';
-- dbms_output.put_line('- SQL: '||v_sql);
execute immediate v_sql;
-- dbms_output.put_line('- Updated table to_be_deleted, row marked deleted');
-- dbms_output.put_line('- End of iter '||to_char(v_iter));
dbms_output.put_line('----------');
-- call function delete_bott_row recursively
v_ret_cde := delete_bott_row;
return 0;
exception
when no_data_found then
dbms_output.put_line('- Table to_be_deleted is empty, delete cascade has completed successfully.');
v_ret_cde := 0;
return 0;
when e_const_viol then
v_sqlcode := SQLCODE;
v_sqlerrm := SQLERRM;
v_ret_cde := v_sqlcode;
dbms_output.put_line('>Constraint Violation. Record has children');
-- dbms_output.put_line('Error code: '||to_char(v_sqlcode));
v_cfkname := substr(v_sqlerrm,instr(v_sqlerrm,'.')+1,instr(v_sqlerrm,')') - instr(v_sqlerrm,'.')-1);
dbms_output.put_line('>Child FK name: '||v_cfkname);
select table_name, column_name
into v_ctname, v_cfkcname
from user_cons_columns
where constraint_name=v_cfkname;
dbms_output.put_line('>Child table name: '||v_ctname||'. FK column name: '|| v_cfkcname);
select constraint_name, column_name
into v_ppkname, v_ppkcname
from user_cons_columns
where constraint_name = (select r_constraint_name
from user_constraints
where constraint_name=v_cfkname);
dbms_output.put_line('>Parent PK/UK name: '||v_ppkname||'. Parent PK/UK column: '||v_ppkcname);
v_sql := 'insert into to_be_deleted(tname, rid, lvl, seq_ins, flg_del) '||
'select '''||v_ctname||''', rowid, '||to_char(v_plvl+1)||', rownum, ''N'' '||
'from '||v_ctname||' '||
'where '||v_cfkcname||' =any (select '||v_ppkcname||' from '||v_ptname||' where rowid =any (select rid from to_be_deleted where tname = '''||v_ptname||'''))';
-- dbms_output.put_line('- SQL: '||v_sql);
execute immediate v_sql;
select count(*)
into v_ins
from to_be_deleted
where lvl = v_plvl+1
and tname = v_ctname
and flg_del = 'N';
dbms_output.put_line('>Found '||to_char(v_ins)||' child records which were added to table to_be_deleted');
v_ret_cde := delete_bott_row;
return v_ret_cde;
when e_max_iter_reached then
dbms_output.put_line('Maximum iterations reached. Terminating procedure.');
raise;
when others then
raise;
end delete_bott_row;
begin
dbms_output.put_line('Beginning');
dbms_output.put_line('================================');
-- validate p_table
begin
select 'Y'
into dummy
from user_tables
where table_name=upper(p_tname);
exception
when no_data_found then
v_param_val := 1;
dbms_output.put_line('Table '||p_tname||' does not exist.');
raise e_bad_params;
end;
dbms_output.put_line('- Parameter p_tname validated');
-- validate p_where
begin
execute immediate 'select ''Y'' from '||p_tname||' where '||p_where INTO dummy;
exception
when no_data_found then -- where clause returns no records
dbms_output.put_line('Record(s) not found. Check your where clause parameter');
v_param_val := 2;
raise e_bad_params;
when too_many_rows then -- found multiple records means it is ok
null;
when others then -- any other records means where clause has something wrong.
dbms_output.put_line('Where clause is malformed');
v_param_val := 2;
raise e_bad_params;
end;
dbms_output.put_line('- Parameter p_where validated');
if v_param_val > 0 then raise e_bad_params; end if;
v_iter := 0;
v_plvl := 1;
v_seq_del := 0;
v_sql := 'insert into to_be_deleted(tname, rid, lvl, seq_ins, flg_del) select '''||upper(p_tname)||''', rowid, '||to_char(v_plvl)||', rownum, ''N'' from '||p_tname||' where '||p_where;
dbms_output.put_line('- Inserting initial record');
dbms_output.put_line('- SQL: '||v_sql);
execute immediate v_sql;
dbms_output.put_line('- Record(s) inserted');
dbms_output.put_line('- Calling function delete_bott_row to delete last row of table to_be_deleted');
dbms_output.put_line('-----------------------------------');
v_ret_cde := delete_bott_row;
-- dbms_output.put_line('- Back from function delete_bott_row');
-- dbms_output.put_line('Return code: '||to_char(v_ret_cde));
dbms_output.put_line('- End of procedure');
exception
when e_bad_params then
dbms_output.put_line('Bad parameters, exiting.');
end;
show errors
spool prc_delete_cascade.log
-- Call to the procedure
exec prc_delete_cascade('xent','xent_id between 1669 and 1670')
select tname "Table Name", count(*) "Rows deleted"
from to_be_deleted
group by tname;
spool off
set lines 120
select *
from to_be_deleted
order by seq_del;
prompt Now commit or rollaback deletions.
-- commit;
-- rollback;Edited by: Rodolfo4 on Mar 23, 2011 10:45 AMInteresting.
I see a few areas where this could be useful. Elimiating specific test records from a Test DB for example.
Some comments:
<li>Since this is a recursive logic you must add a stop criteria. In this case I would add a max iteration variable. If that one is reached, raise an error message and let the procedure stop with that error.</li>
<li>The when others exception at the end should be removed completely</li>
<li>The when others exception in the middle should be replaced by a specific exception that handles the -2292 error</li>
<li>A list of tables where no record should be deleted could be usefull. If the logic would encounter such a table, it should also stop. This would be to prevent that data from some system critical tables could be deleted per accident.</li>
<li>The reference from the FK constraint to the PK constraint should include the table name and if possible the owner (as long as you use user_* views the owner is always the same. But we could extend this to the ALL_* views). I never met a system where different tables have the identical FK constraint names, however just make this fool proof.</li> -
Discontinuation indicator and follow up material.
Hi,
I am facing the strange issue for which i need your expertise. The requirement is like:
1. "X" material is discontinued and "Y" is as follow-up in two plants A & B. Discontinaution group and follow-up group has also been assigned in the BOM.
2. Now The client want to reverse the settings . means "Y" should be discontinued and "X" should be follow-up in both plants A & B.
Now I have removed the discontinuation indicator and follow up material from "X" in both plants. But when I am going to discontinue the "Y" material and putting " X" as a follow-up material, The system is giving the message "The specified follow-up material results in recursiveness
Message no. M3609
Diagnosis
You have entered a follow-up material. However, the BOM explosion for the follow-up material leads to the discontinued material, resulting in unpermissible recursiveness.
Procedure
Enter another follow-up material or cancel the entry.
Please suggest me where I am missing in my settings and what is the reason for this message.
Regards
Deepak SharmaDear ,
Check the following :
1.Validity of the Bill Of Material or any deletion flag is set in the present BOM.
2.Please check the following SAP notes :
Note 161742 - Consulting note: BOM recursion/low-level code 999
Note 839879 - Trace 'BOM is recursive'
Note 139517 - Recursiveness for follow-up materials
Note 42891 - Recursiveness check
Hope this will help you to figure it out
Regards
JH -
How to read the hierarchy data from the same table using loop in AMDP method
Hi All,
We have a requirement to get the top partner from BUT050 table.
Here the Top parent is nothing but the top most in the hierarchy of the partners from BUT050.
Example:
For partner 1234 (BUT050-PARTNER1) there is partner 3523(BUT050-PARTNER2) one level above
For partner 3523(BUT050-PARTNER1) there is partner 4544 (BUT050-PARTNER2) last level .
so in this case for the partner 1234 the Top parent is 4544 .
I have created AMDP Procedure method to get the top-parnet and below given is the logic implemented in AMDP method.
Here i have implemented a recursive logic with the WHILE loop to get the top most hierarchy partner from the same table BUT050
IV_Parent is the input partner and ev_top_parent is the output value.
AMDP Procedure Method:
DECLARE lv_date VARCHAR(8) := TO_VARCHAR (current_date, 'YYYYMMDD');
DECLARE found INT := 1;
iv_partner1 = SELECT partner1 FROM but050
WHERE partner2 = iv_partner
AND reltyp = :iv_hierarchy
AND date_to >= :lv_date
AND date_from <= :lv_date;
WHILE found <> 0 do
select partner1 into ev_top_parent from :iv_partner1;
iv_partner1 = SELECT partner1 FROM but050
WHERE partner2 in ( select partner1 from :iv_partner1 where partner1 is not null)
AND reltyp = 'ZBP004'
AND date_to >= :lv_date
AND date_from <= :lv_date;
select COUNT ( partner1 ) INTO found FROM :IV_PARTNER1;
END WHILE;
This method is working fine, but here it is only taking one single partner and getting the top parent as output.
Now i would like to convert this mehtod so as to accept n number of partners (not one single partner) as input and should process each partner to get the top parent.
Could anyone guide me how can i handle the given AMDP method further so as to work some how it is within another loop from other AMDP method.
Thanks.
Regards,
Laxman.PHi
Go to SE11 and enter the hierarchy table name.
/BIC/H....(infoobject name)...and execute the table and select table entry and delete all....
Thanks
TG -
A help with a hierarchical query
I've got two tables:
FOLDERS where relevant fields are: folderId, parentFolderId, folderQuota
and DOCUMENTS where the relevant fields are: folderId, size
FOLDERS is hierarchical - parentFolderId of a child's folder is set to folderId of the parent
folderQuota is nullable (quota not set)
Now, I need to execute a query with the following recursive logic
<i>function calcQuota (folderIdpar, isFirstpar) {
if (not isFirstpar) and (folderQuota of folder with folderIdpar is not null) return folderQuota;
return size of all documents where folderId = folderIdpar + calcQuota (folderId of all children, false);
}</i>
(I hope the pseudocode is understandable - the query is executed as <i>calcQuota(originalFolderId, true)</i>).
Now, my question is if I can achieve it with a single hierarchical query, or if I have to implement it as a recursive stored procedure.
Thanks!
P.S. I'm using Oracle XE (10g)OK,
I will need to create it (in real life it is created by an application), so I hope I will make it correct. If not, it should be easy to fix.
create table folders (
folder_id number primary key
parent_folder_id number,
quota number
create table documents (
document_id number primary key
folder_id number,
size number
INSERT INTO folders (folder_id, quota) VALUES (1, 1);
INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (2, 1, 2);
INSERT INTO folders (folder_id, parent_folder_id) VALUES (3, 1);
INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (4, 2, 4);
INSERT INTO folders (folder_id, parent_folder_id) VALUES (5, 2);
INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (6, 3, 8);
INSERT INTO folders (folder_id, parent_folder_id) VALUES (7, 3);
INSERT INTO documents (document_id, folder_id, size) VALUES (1, 1, 16);
INSERT INTO documents (document_id, folder_id, size) VALUES (2, 2, 32);
INSERT INTO documents (document_id, folder_id, size) VALUES (3, 3, 64);
INSERT INTO documents (document_id, folder_id, size) VALUES (4, 3, 128);
INSERT INTO documents (document_id, folder_id, size) VALUES (5, 4, 256);
INSERT INTO documents (document_id, folder_id, size) VALUES (6, 5, 512);
INSERT INTO documents (document_id, folder_id, size) VALUES (7, 6, 1024);
INSERT INTO documents (document_id, folder_id, size) VALUES (8, 7, 2048);
running the query for folder_id = 1 should return 1 + 2 + 64 + 128 + 8 + 2048 = 2251
running the query for folder_id = 2 should return 4 + 512 = 516
I have decided for this data, because it allows to track what values (folder.quota or document.size) is included in the result.
(it is the knapsack problem - see http://en.wikipedia.org/wiki/Knapsack_problem)
P.S. I'm leaving for three weeks, so I will come back after that. -
I'm trying to create a zip utility which takes in a certain directory's location and zips up all files and sub-directories. I have coded the recursive logic needed to also zip the subdirectories but I'm getting a FileNotFound exception with the sub-directories. here is an example: "java.io.FileNotFoundException: C:\out\images (Access is denied)" Please let me know if there is any security settings which I can override to prevent this error.
Looks like you are trying to open a directory.
You should only open files.
if (a_file.isDirectory()) {
zipDirectory(a_file.toString(), out);
else {
// do the file-zipping stuff
// method checks recursively for dirs
zipDirectory(File fi, ZipOutputStream out){
// loop through the dir entries : String[] entries = fi.list();
if(entry.isDirectory())
zipDirectory(..)// recursive call
else
// fo the file-zipping stuff
}Try that if you're doing it already, and repost if problem subsists. -
How to build query to get tree architecture of self referencing table
Dear all,
I have the following table design :
This is a self referencing table representing a set of SubCategories which can have parent sub categories or not. I did not show here the Category table.
If the Subcategory has the ParentSubCategory ID = null, then this is a root subcategory otherwise it is a child of a parent sub category.
What I am looking for is the easy way to display the structure level by ProductCategoryID ?
Thanks for helpsyou can use a recursive logic based on CTE for that
something like this would be enough
;WITH ProdSubCat_Hiererchy
AS
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psc.Name AS varchar(max)) AS [Path],1 AS [level]
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
WHERE psc.ParentSubCategoryID IS NULL
UNION ALL
SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psch.[Path] + '/' + psc.Name AS varchar(max)) AS [Path],psch.[level] + 1
FROM ProductSubCategory psc
INNER JOIN Category c
ON c.CategoryID = psc.ProductCategoryID
INNER JOIN ProdSubCat_Hiererchy psch
ON psch.ProductSubCategoryID = psc.ParentSubCategoryID
SELECT *
FROM ProdSubCat_Hiererchy
ORDER BY LEFT([Path],CHARINDEX('/',[Path]+'/')-1),[Level]
OPTION (MAXRECURSION 0)
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
Maybe you are looking for
-
XML form in not getting displayed in the option while assigning
Hello Experts, I have created a XML form and now assigning it to a folder. While assigning Folder>new>forms> .. here I can see other forms but not the new one which I have recently created. Please let me know I can assign the newly created form to th
-
How to find leap year in sql query
How to find leap year in sql query
-
Just tried to import a new CD into my iTunes music library, but get this error code "error occurred while converting file. You do not have the privilege to make changes"....any thoughts? Have not tried to change anything- only import CD ??
-
Help:JCombobox in table cell
I have a column using combobox as cell editor in jtable, the combo box 's content is different based on the row user selects, for example, user selects the first row, the combo box will show selections" hi, hello", when user selected the second row,
-
BC email and recovery email are the same
Client has setup his email account in BC and unfortunately his recovery email is the same as the BC email. He is locked out of his email because he changed the password and cannot remember it. Going through the password recovery or reset module is