Oracle Applications 11i SQL Scripts
Transcript of Oracle Applications 11i SQL Scripts
Table of ContentsScript to Start and Stop the Application, Database Servers......................4
Checking Credit Card Number validity in Internet Expenses, iPayments using Luhn algorithm (modulus 10).................................................5
The Concurrent Jobs Ran Yesterday and Failed – SQL script & Unix Shell Script..............................................................................................................................7
Key Flex Field Structures & How to Retrieve Information..........................9
Submitting Concurrent Request Using FND_CONCURRENT.WAIT_FOR_REQUEST Sample Code................................12
Production to Development Refresh/Clone Parameter Change SQL Script........................................................................................................................................14
Simple Query to find FND_LOOKUP Values........................................................16
Sample Script to Debug the Procedure, Packages Running At Backend...................................................................................................................................17
Another SQL script to find the profile option values....................................18
How do I see the debug messages either in log file or output file in oracle applications?.........................................................................................................20
How To Add Responsibility to USER using pl/sql? – Oracle Applications..........................................................................................................................20
Here Is A Sample Unix / Linux Script That Checks The Payment Settlement File And Acknowledgement File......................................................22
Steps To Register Shell Script As A Concurrent Program..........................23
GL Date Move for Lockbox Records – Oracle Applications tips – SQL..25
How to secure login with oracle SQL*Plus with a password On UNIX and Linux platforms.........................................................................................................26
Oracle Applications Schema Password Change Utility – (FNDCPASS).................27
What is FNDLOAD and how to use it?.............................................................................29
Receipt On Account & Unapplied – SQL Query............................................................33
Total Credit related to a customer – sql query – Oracle Applications..................34
Tuning & Performance – Gather Statistics importance.............................................35
Locks on oracle database & Oracle applications Processing..................................36
FND_GLOBAL: WHO Column Maintenance and Database Initialization – Oracle Applications..............................................................................................................................43
How do you check the profile option values using sql – Oracle Applications?. 43
How can we find the receipts related to a transmission?........................................45
Receipt API in Oracle Receivables....................................................................................46
Find responsibilities associated with the users – using sql.....................................46
How to run a unix host command from oracle plsql package?..............................46
Validate the credit card (oracle 10 g plsql code) – working!..................................47
Simple PL/SQL script to remove the unwanted non-ascii characters from oracle or 11i database.........................................................................................................50
Find all the receipt methods associated with a receipt class.................................51
What are the profile setup values for ipayment gateway (oracle applications)?......................................................................................................................................................51
How to find the receipt stuck in between stages?.....................................................52
List all the concurrent Jobs ran by user.........................................................................53
How to find the log file and output file of a concurrent Job id?.............................53
Handy tkprof sql creating script using bash shell unix, linux with oracle environment.............................................................................................................................54
LUHN Algorithm Logic...........................................................................................................56
How To Extract,Using Bash/Unix/Linux Shell Scripting, The Oracle Data Like Excel Report And Send As Email Attachment?............................................................58
Oracle applications (11i) Invalid credit cards in bank records report..................59
Oracle applications (11i) daily credit card failure report – ipayment gateway 62
Oracle Application Performance Tuning Scripts..........................................................65
Tuning & Performance – Gather Statistics importance.........................................69
Current Period Status of Application (oracle 11i).......................................................70
Pending normal jobs running (oracle 11i) in oracle applications..........................71
Get Credit Card Number for a customer number (oracle 11i)................................71
Get Credit Card Number for an invoice (oracle 11i)..................................................72
Auto shipment notification to companies using oracle applications – Concurrent Job shell script..................................................................................................73
Send e-mail messages and attachments from PL/SQL.............................................76
Whether GL Period is open or not as of sysdate?.......................................................77
GL Handy SQL’s –...................................................................................................................78
Get Operating Unit & Legal Entity....................................................................................78
Profile option check – Initialization SQL Statement – Oracle..................................79
List Reponsibilities for an user..........................................................................................80
List the responsibilities that can run a given concurrent program......................80
How to Verify a Patch applied?.........................................................................................80
Set an OPERATING UNIT......................................................................................................81
Script to Start and Stop the Application, Database Servers Oracle Applications: Script to Start and Stop the Application, Database Servers: This is script is tested in oracle applications version 12.1.1 on linux 64 bit system cent OS. Oracle software, by default, gives startup script for database and applications server for each server basis. Once you have installed the server, and established your working site, you need to Database, listeners and application servers in sequence and process the same kind of execution to stop the system. I tried to semi automate the system by having this script in place so that I can startup the servers in single command and stop them in single command. The script internally validates and run automatically. As a side note, you can also automate the system by giving this script or script link in your link server boot startup area (which is not shown here). Here are the scripts:
#!/bin/bash########################################################## Developed by # This start all the oracle processes one by one########################################################### If you pass any parameter the application check is removed!# You are over ruling the execution#IF [ $@ > 0 ]then echo "Processing"else DBRUNNING=`ps -ef ‘ grep -i VISDB ‘ wc -l` IF [ ${DBRUNNING} -gt 1 ] then echo "Application and database are already running. You can not start again." exit 1 fifi
CURDIR=`pwd`
DBDIR=/var/www/html/oracle12/db/tech_st/11.1.0/appsutil/scripts/VISDB_oracle12
APDIR=/var/www/html/oracle12/inst/apps/VISDB_oracle12/admin/scripts
cd ${DBDIR}
#Start Database listener process addlnctl.sh start VISDB
#Start Database process addbctl.sh start
cd ${APDIR}
#Start Applications processes adstrtal.sh apps/<pwd>
cd ${CURDIR}
Here is the stop apps script
#!/bin/bash########################################################## Developed by # This stop all the oracle processes one by one########################################################### If you pass any parameter the application check is removed!# You are over ruling the execution
#IF [ $@ > 0 ]then echo "Processing"else DBRUNNING=`ps -ef ‘ grep -i VISDB ‘ wc -l` IF [ ${DBRUNNING} -eq 1 ] then echo "Application and database are not running. Please check." exit 1 fifi
CURDIR=`pwd`
DBDIR=/var/www/html/oracle12/db/tech_st/11.1.0/appsutil/scripts/VISDB_oracle12
APDIR=/var/www/html/oracle12/inst/apps/VISDB_oracle12/admin/scripts
cd ${APDIR}
#Stop Applications processes adstpall.sh apps/<pwd>
cd ${DBDIR}
#Stop Database process addbctl.sh stop
#Stop Database listener process addlnctl.sh stop VISDB
cd ${CURDIR}
Checking Credit Card Number validity in Internet Expenses, iPayments using Luhn algorithm (modulus 10)
Is there any method to spot check validity of the card number, prior to asking client to check with the credit card company? Team that follows LUHN10 ALGORITHM (http://en.wikipedia.org/wiki/Luhn_algorithm) for validating the checksum on the card numbers. If the checksum ends with 0 modulus of the checksum is congruent to zero then the number is valid (For e.g. 70 MOD 10 = 0). In general all the credit card brands follow this algorithm. As an illustration, if the account number is 49927398716, it will be validated as follows.
Double every second digit: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18Sum all digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70Take the sum modulo 10: 70 mod 10 = 0; the account number is valid.
I have created a simple shell script ran as concurrent job which sends the list daily or periodically.
#!/bin/sh## Author: # Test email for future cronjobs#FILENAME="Company_Invalid_credit_card.xls"source /usr/bin/production.envif [ -f $FILENAME ]then rm -rf $FILENAME echo "Old Data File ($FILENAME) deleted…"fiecho $FILENAMEsqlplus -s username/password@productiondb<<EOFSET echo OFFset serveroutput onSET feedback off SET heading offSET linesize 221 SET pagesize 0 SET newpage 0
alter session set current_schema=apps;
spool $FILENAME
DECLARE p_api_version NUMBER := 1.0; p_init_msg_list VARCHAR2(240) := NULL; x_return_status VARCHAR2(240); x_msg_count NUMBER; x_msg_data VARCHAR2(240); x_cc_valid BOOLEAN; x_cc_type VARCHAR2(240); x_cc_valid_text VARCHAR2(20);CURSOR trx_main IS select decode(rct.org_id,262,‘Company China Operating Unit’,283,‘Company Europe Operating Unit’,303,‘Company India Operating Unit’,307,‘Company UK Operating Unit’,311,‘Company Australia Operating Unit’,315,‘Company Japan Operating Unit’,319,‘Company Hong Kong Operating Unit’,223,‘Company US Operating Unit’) Operating_unit, rc.customer_name customer, rct.trx_number invoice_number, aps.AMOUNT_DUE_REMAINING, apa.bank_account_name bank_name, apa.bank_account_num credit_card_number, apa.inactive_date credit_validaity_date, acol.NAME collector_name from AP_BANK_ACCOUNTS_ALL apa, ra_customer_trx_all rct, ra_customers rc, ar_payment_schedules_all aps, ra_batch_sources_all rbs, AR_CUSTOMER_PROFILES ACP, AR_COLLECTORS ACOL where 1=1 AND ACP.CUSTOMER_ID = rc.CUSTOMER_ID AND ACP.COLLECTOR_ID = ACOL.COLLECTOR_ID
AND ACP.SITE_USE_ID IS NULL and rct.batch_source_id = rbs.batch_source_id and rct.customer_trx_id = aps.customer_trx_id and rct.org_id = aps.org_id and apa.bank_account_id = rct.customer_bank_account_id and rc.customer_id = rct.bill_to_customer_id AND aPS.gl_date_closed = TO_DATE(‘4712/12/31′, ‘YYYY/MM/DD’) AND aps.selected_for_receipt_batch_id IS NULL and aps.status = ‘OP’ and rct.attribute9=‘CREDIT CARD’ AND RCT.ORG_ID > 202 AND aps.reserved_type IS NULL AND aps.reserved_value IS NULL and aps.AMOUNT_DUE_REMAINING > 0 order by aps.AMOUNT_DUE_REMAINING desc;BEGIN DBMS_OUTPUT.ENABLE (1000000); dbms_output.put_line(‘Operating Unit’”chr(9)”‘Invoice Number’”chr(9)”‘Customer Name’”chr(9)”‘Credit Card Number’”chr(9)”‘Validatity Date’”chr(9)”‘Amount_Due_Remaining’”chr(9)”‘Status’”chr(9)”‘Collector’); FOR invoice_main IN trx_main LOOP iby_cc_validate.ValidateCC ( p_api_version, p_init_msg_list,invoice_main.credit_card_number,invoice_main.credit_validaity_date,x_return_status,x_msg_count,x_msg_data, x_cc_valid, x_cc_type ); if x_cc_valid = true then x_cc_valid_text := ‘VALID’; else x_cc_valid_text := ‘NOT VALID’; dbms_output.put_line(to_char(invoice_main.Operating_unit)”chr(9)”to_char(invoice_main.invoice_number)”chr(9)”invoice_main.customer”chr(9)”to_char(invoice_main.credit_card_number)”chr(9)”to_char(invoice_main.credit_validaity_date)”chr(9)”to_char(invoice_main.AMOUNT_DUE_REMAINING)”chr(9)”x_cc_valid_text”chr(9)”invoice_main.collector_name); end if; END LOOP;EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘Error Occurred’ ” SQLERRM ); END;/
EOF
if [ -f $FILENAME ]then uuencode $FILENAME $FILENAME ‘ mail -s "Company Invalid Credit Cards Attached to Invoices ! Reported on `date` " "[email protected]" -c "[email protected]" fi
The Concurrent Jobs Ran Yesterday and Failed – SQL script & Unix Shell Script
Pending normal jobs running (oracle 11i) in oracle applications Oracle applications – List all the concurrent Jobs ran by user.
Oracle Applications: Submitting Concurrent Request Using FND_CONCURRENT.WAIT_FOR_REQUEST Sample Code
List the responsibilities that can run a given concurrent program Auto shipment notification to companies using oracle applications –
Concurrent Job shell script
I often use this script to find the concurrent jobs ran yesterday and Failed. You can also automate the script into unix shell or some oracle alerts.
SELECTfu.user_name,fcpt.USER_CONCURRENT_PROGRAM_NAME,fcpt.description,fcp.CONCURRENT_PROGRAM_NAME,fcr.REQUEST_ID,round((fcr.actual_completion_date – decode (trunc(fcr.request_date),fcr.requested_start_date,fcr.request_date,fcr.requested_start_date))*60*24) WaitTimeMIN,DECODE(fcr.PHASE_CODE,‘C’,‘Completed’,‘R’,‘Running’,fcr.PHASE_CODE) PHASE_CODE,DECODE(fcr.STATUS_CODE,‘C’,‘Completed’,‘R’,‘Running’,‘W’,‘Paused’,‘E’,‘Error’,‘G’, ‘Warning’, fcr.STATUS_CODE) STATUS_CODE,to_char(fcr.request_date,‘DD-MON-YYYY HH24:MI:SS’) request_date,to_char(fcr.requested_start_date,‘DD-MON-YYYY HH24:MI:SS’) start_time,to_char(fcr.actual_completion_date,‘DD-MON-YYYY HH24:MI:SS’) complete_timeFROMfnd_concurrent_requests fcr,fnd_concurrent_programs fcp,fnd_concurrent_programs_tl fcpt,fnd_user fuWHERE 1=1AND fcp.CONCURRENT_PROGRAM_ID=fcr.CONCURRENT_PROGRAM_IDAND fcpt.CONCURRENT_PROGRAM_ID=fcp.CONCURRENT_PROGRAM_IDAND fcr.requested_by = fu.user_idAND trunc(fcr.request_date) BETWEEN sysdate – 1 AND sysdateAND fcr.status_code IN (‘E’,‘G’)ORDER BY fcr.status_code,fcp.CONCURRENT_PROGRAM_NAME,fcr.REQUEST_ID;
Here is the shell script that you can put it in crontab to run daily to send you email
#!/bin/sh## Author: # Test email for future cronjobs#FILENAME=DailyReportFILETEXT=$FILENAME.txtsource /usr/local/bin/production.env
sqlplus -s username/password@database <<EOF –alter session set current_schema=apps;
SET echo OFFSET feedback OFF SET heading onSET linesize 221 SET pagesize 55 SET newpage 0
spool $FILETEXT
column today new_value CURR_DATE noprintSELECT to_char(sysdate,‘DD-MON-YYYY HH24:MI:SS’) today from dual;
TTITLE left ‘JILERRCC’ CENTER ‘Corporation’ – RIGHT ‘DATE:’ CURR_DATE skip 1 - CENTER ‘Concurrent Jobs Errored Yesterday’ - RIGHT ‘PAGE:’ format 999 SQL.PNO skip 1 -
column user_name format a10column USER_CONCURRENT_PROGRAM_NAME format a40column description format a50column CONCURRENT_PROGRAM_NAME format a10column REQUEST_ID format 99999999column WaitTimeMIN format 9999.99column PHASE_CODE format a10column STATUS_CODE format a10column request_date format a20column start_time format a20column complete_time format a20
BREAK ON status_code SKIP 1
SELECT fu.user_name, fcpt.USER_CONCURRENT_PROGRAM_NAME, fcpt.description, fcp.CONCURRENT_PROGRAM_NAME, fcr.REQUEST_ID, round((fcr.actual_completion_date – decode (trunc(fcr.request_date),fcr.requested_start_date,fcr.request_date,fcr.requested_start_date))*60*24) WaitTimeMIN, DECODE(fcr.PHASE_CODE,‘C’,‘Completed’,‘R’,‘Running’,fcr.PHASE_CODE) PHASE_CODE, DECODE(fcr.STATUS_CODE,‘C’,‘Completed’,‘R’,‘Running’,‘W’,‘Paused’,‘E’,‘Error’,‘G’, ‘Warning’, fcr.STATUS_CODE) STATUS_CODE, to_char(fcr.request_date,‘DD-MON-YYYY HH24:MI:SS’) request_date, to_char(fcr.requested_start_date,‘DD-MON-YYYY HH24:MI:SS’) start_time, to_char(fcr.actual_completion_date,‘DD-MON-YYYY HH24:MI:SS’) complete_timeFROM fnd_concurrent_requests fcr, fnd_concurrent_programs fcp, fnd_concurrent_programs_tl fcpt, fnd_user fuWHERE 1=1
AND fcp.CONCURRENT_PROGRAM_ID=fcr.CONCURRENT_PROGRAM_IDAND fcpt.CONCURRENT_PROGRAM_ID=fcp.CONCURRENT_PROGRAM_IDAND fcr.requested_by = fu.user_idand trunc(fcr.request_date) between sysdate – 1 and sysdateAND fcr.status_code in (‘E’,‘G’)order by fcr.status_code,fcp.CONCURRENT_PROGRAM_NAME,fcr.REQUEST_ID;
spool off;EOFmail -s "Yesterday Concurrent Program status! Reported on `date` " [email protected] < $FILETEXT
Key Flex Field Structures & How to Retrieve Information.
Here is some of quite commonly used AOL FND ( Foundation) tables and their usage. There are many other tables also in FND but here i am putting only few commonly used tables. for other table if needed we can dig further.
FND_ID_FLEXS stores registration information about key flexfields. Each row includes the four–character code that identifies the key flexfield, the title of the flexfield (by which a user identifies theflexfield), the name of the combinations table that contains the key flexfield columns, and the name of the structure defining (MultiFlex) column for the flexfield (SET_DEFINING_COLUMN_NAME). Each row also contains values that identify the application that owns the combination table and the application that owns the key flexfield, a table–type flag that specifies whether the combinations table is specificor generic (S or G), whether dynamic inserts are feasible for the flexfield(Y or N), whether the key flexfield can use ID type value sets, and the name of the unique ID column in the combinations table. You need one row for each key flexfield in each application. Oracle Application ObjectLibrary uses this information to generate a compiled key flexfield definition
FND_ID_FLEX_SEGMENTS: FND_ID_FLEX_SEGMENTS stores setup information about keyflexfield segments, as well as the correspondences between application table columns and the key flexfield segments the columns are used for. Each row includes a flexfield application identifier, the flexfield code,which identifies the key flexfield, the structure number(ID_FLEX_NUM), the value set application identifier, the segment number (the segment’s sequence in the flexfield window), the name of the column the segment corresponds to (usually SEGMENTn, where n is an integer). Each row also includes the segment name, whether security is enabled for the segment, whether the segment is required, whether the segment is one of a high, low segment pair, whether the segment is displayed, whether the segment is enabled (Y or N), type of default value, display information about the segment such as prompts and display size, and the value set the segment uses. Each row also includes a flag for whether the table column is indexed; this value is normally Y. You need one row for each segment of each structure for each flexfield. Oracle Application Object Library uses this information to generate a compiled key flexfield definition to store in the FND_COMPILED_ID_FLEXS table Thanks – Shivmohan Purohit
FND_ID_FLEX_STRUCTURES : FND_ID_FLEX_STRUCTURES stores structure information about keyflexfields. Each row includes the flexfield code and the structurenumber (ID_FLEX_NUM), which together identify the structure, and the name and description of the structure. Each row also includes values that indicate whether the flexfield structure is currently frozen, whether rollup groups are frozen (FREEZE_STRUCTURED_HIER_FLAG), whether users can dynamically insert new combinations of segment values through the flexfield pop–up window, and whether the flexfield should use segment cross–validation rules. Each row also contains information about shorthand flexfield entry for this structure, including whether shorthand entry is enabled, the prompt for the shorthand window, and the length of the shorthand alias field in the shorthandwindow. You need one row for each structure of each key flexfield. Oracle Application Object Library uses this information to generate acompiled key flexfield definition to store in the FND_COMPILED_ID_FLEXS table
FND_FLEX_VALUES stores valid values for key and descriptive flexfield segments. Oracle Application Object Library uses this table when users define values for independent or dependent type value sets. Oracle Application Object Library also uses this table when users define parent values for ranges of child values that exist in a validation table(Oracle Application Object Library stores the parent values in this table). Each row includes the value (FLEX_VALUE) and its hierarchy level if applicable as well as the identifier of the value set the value belongs to. If the value is a dependent value, PARENT_FLEX_VALUE_LOW contains the independent value this value depends upon. Oracle Application Object Library does not use the PARENT_FLEX_VALUE_HIGH column. If ENABLED_FLAG contains N, this value is currently invalid, regardless of the start and end dates.
If ENABLED_FLAG contains Y, the start and end dates indicate if this value is currently valid.SUMMARY_FLAG indicates if this value is a parent value that has child values, and STRUCTURED_HIERARCHY_LEVEL contains the rollup group the parent value belongs to, if any (1 through 9). COMPILED_VALUE_ATTRIBUTES contains the compiled values of anysegment qualifiers assigned to this value. These values are in a special Oracle Application Object Library format, and you should never modify them.
VALUE_CATEGORY and ATTRIBUTE1 through ATTRIBUTE50 are descriptive flexfield columns, where VALUE_CATEGORY is the context (structure defining) column.
These descriptive flexfield columns do not contain values unless you have defined the descriptive flexfield at your site. You need one row for each independent, dependent or parent value belonging to a value set.Oracle Application Object Library uses this information to ensure that users enter valid values in flexfield segments
FND_FLEX_VALUE_HIERARCHIES stores information about child value ranges for key flexfield segment values. Each row includes an identification of the parent value the range belongs to, as well as the low and high values that make up the range of child values. FLEX_VALUE_SET_ID identifies the value set to which the parent value belongs. You need one row for each range of child values (you can have more than one row for each parent value). Oracle Application Object Library provides this information for applications reporting purposes.
SELECT B.APPLICATION_ID, B.ID_FLEX_CODE, B.ID_FLEX_NUM, B.ID_FLEX_STRUCTURE_CODE, B.CONCATENATED_SEGMENT_DELIMITER, B.CROSS_SEGMENT_VALIDATION_FLAG, B.DYNAMIC_INSERTS_ALLOWED_FLAG, B.ENABLED_FLAG, B.FREEZE_FLEX_DEFINITION_FLAG, B.FREEZE_STRUCTURED_HIER_FLAG, B.SHORTHAND_ENABLED_FLAG, T.ID_FLEX_STRUCTURE_NAME, T.DESCRIPTION FROM FND_ID_FLEX_STRUCTURES_TL T, FND_ID_FLEX_STRUCTURES B WHERE B.APPLICATION_ID = T.APPLICATION_ID AND B.ID_FLEX_CODE = T.ID_FLEX_CODE AND B.ID_FLEX_NUM = T.ID_FLEX_NUM AND T.LANGUAGE = userenv(‘LANG’) AND B.ENABLED_FLAG = ‘Y’ AND B.FREEZE_STRUCTURED_HIER_FLAG = ‘Y’ AND B.ID_FLEX_CODE = ‘GL#’ AND B.ID_FLEX_NUM = &&number
Here are some more SQLs to find the GL combinations structures:
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_Department%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_Account%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_Future%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_Location_FA%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_Country_FA%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_State_FA%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_ID
AND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
SELECT s.FLEX_VALUE_SET_ID,s.FLEX_VALUE_SET_NAME, v.FLEX_VALUE, t.DESCRIPTIONFROM fnd_flex_values v,fnd_flex_value_sets s,fnd_flex_values_tl t WHERE FLEX_VALUE_SET_NAME LIKE ‘%&&Company_City_FA%’AND s.FLEX_VALUE_SET_ID = v.FLEX_VALUE_SET_IDAND t.FLEX_VALUE_ID = v.FLEX_VALUE_IDORDER BY FLEX_VALUE
Submitting Concurrent Request Using FND_CONCURRENT.WAIT_FOR_REQUEST Sample Code
When submitting concurrent requests using PL/SQL, it is often desired to have the parent process wait until all the child processes have completed before completing itself. The following describes the function used to accomplish this.
Refer Metalink 1021956.6: The following describes how to submit concurrent requests using PL/SQL and have the parent request ‘wait’ until each of the child processes have completed before it completes.
Use the FND_CONCURRENT.WAIT_FOR_REQUEST function documented in the Oracle Applications Developer’s Guide, RELEASE 11i, Page 21-8 See the FND_CONCURRENT.WAIT_FOR_REQUEST function description.
Summary <strong>FUNCTION FND_CONCURRENT.WAIT_FOR_REQUEST</strong> (request_id IN number DEFAULT NULL, interval IN number DEFAULT 60, max_wait IN number DEFAULT 0, phase OUT varchar2, STATUS OUT varchar2, dev_phase OUT varchar2, dev_status OUT varchar2, message OUT varchar2) RETURN BOOLEAN;
DescriptionWait for the request completion, then return the request phase/status andcompletion message to the caller. Also call sleep between database checks.
Arguments (input)
request_idThe request ID of the program to wait on.
intervalTime to wait between checks. This is the number of seconds to sleep.The default is 60 seconds.
max_waitThe maximum time in seconds to wait for the requests completion.
Arguments (output)
phaseThe user friendly request phase from FND_LOOKUPS.
statusThe user friendly request status from FND_LOOKUPS.
dev_phaseThe request phase as a constant string that can be used for programlogic comparisons.
dev_statusThe request status as a constant string that can be used for programlogic comparisons.
messageThe completion message supplied if the request has completed.
BEGIN l_request_id := fnd_request.submit_request (‘XXCUS’, ‘XXCUSSPOOL’, NULL, NULL, FALSE, p_filename_i, p_seq_i ); END;
p_request_id_o := l_request_id;
fnd_file.put_line (fnd_file.LOG,‘XXCUSSPOOL Submitted. Request_id=’”p_request_id_o”‘ Filename=’”p_filename_i”‘ Seq=’”p_seq_i );
IF p_request_id_o = 0 THEN ec_log_debug (p_filename_i,‘SUBMIT_FILE_CREATION’,4090, ‘XXCUSSPOOL submission failed for ‘”p_filename_i”‘Request_id=’”p_request_id_o ); ELSE l_return := fnd_concurrent.wait_for_request (request_id => p_request_id_o, INTERVAL => 10, max_wait => 300, – Null means wait forever, I normally provide 300 = 5 mins phase => l_phase, STATUS => l_status, dev_phase => l_dev_phase, dev_status => l_dev_status, MESSAGE => l_message ); END IF;
Production to Development Refresh/Clone Parameter Change SQL Script. Big companies that follow Process oriented project management team, with multiple projects executed at phased manner, may face challenges during database refresh from production system to development or test systems. Many programs customized to connect to external systems such as lockbox servers, payment processing servers and other boundary server systems.
After every refresh, it is imperative to change the development systems to point to null or Development external test servers instead of production servers. If this is not done immediately after the database refresh, development data may accidentally reach the production external servers that cause havoc! For example, if some developers start automatic payment/receipt programs in DEV servers that connects to production payment processors, customers may get charged without any product shipped! This is illegal and I had seen, two times in last 10 years, which affects customer confidence!
We have created a simple table that stores development default values and production default values and a simple plsql block that reads the table and changes the default parameter depending on the instances. This can be a manual or automatic run after a refresh by DBAs. In many companies, this is maintained by DBAs. However, using this, Any one responsible can maintain the parameter and DBAs can run the script to change the values. We have even created a form to review, add, edit or delete. Currently, I am not providing the form (*.fmb) but the table and plsql block for your reference.
Download parameterchange.sql
Here is the table script:
DROP TABLE xxcus_con_default_value CASCADE CONSTRAINTS;
CREATE TABLE xxcus_con_default_value( CONC_PROGRAM_NAME VARCHAR2(30 BYTE) NOT NULL, PARAM_NAME VARCHAR2(30 BYTE) NOT NULL, DEV_DEFAULT_VALUE VARCHAR2(240 BYTE), PROD_DEFAULT_VALUE VARCHAR2(240 BYTE), CREATED_BY NUMBER(15) NOT NULL, CREATION_DATE DATE NOT NULL, LAST_UPDATED_BY NUMBER(15) NOT NULL, LAST_UPDATE_LOGIN NUMBER(15), LAST_UPDATE_DATE DATE NOT NULL)
Here is the form:
Here is the PLSQL script:
–Source File :ParameterChange.sql–REM =====================================================================================/* Created on : 09-Jan-2006 *//* Created By : *//* ======================================================================================= */
SET serveroutput ON size 1000000SET arraysize 1SET feed offSET echo off
DECLARE l_instance VARCHAR2(30):= ‘&1′; l_report_only VARCHAR2(30):= ‘&2′;
CURSOR parm_list IS SELECT conc.conc_program_name, conc.param_name, conc.dev_default_value, conc.prod_default_value, arg.DEFAULT_VALUE old_default_value FROM xxcus_con_default_value conc, FND_DESCR_FLEX_COL_USAGE_VL arg WHERE arg.descriptive_flexfield_name = ‘$SRS$.’”conc.conc_program_name AND arg.END_USER_COLUMN_NAME=conc.param_name ORDER BY 1,2;
l_rowid rowid; l_default_value VARCHAR2(240); l_status VARCHAR2(3000):=‘Report Only’;
BEGIN fnd_file.put_line(fnd_file.LOG,‘Instance: ‘”l_instance); fnd_file.put_line(fnd_file.output,‘Instance Name: ‘”l_instance); fnd_file.put_line(fnd_file.output,‘Resport Only Mode: ‘”l_report_only);
fnd_file.put_line(fnd_file.output,‘Program Name Parameter Current Value New Value Status’); fnd_file.put_line(fnd_file.output,‘============ ========= ============= ========= ======’);
FOR rec IN parm_list LOOP IF (l_instance = ‘Production’ ) THEN l_default_value := rec.prod_default_value; ELSE l_default_value := rec.dev_default_value; END IF;
IF (l_report_only <> ‘Yes’) THEN BEGIN UPDATE fnd_descr_flex_column_usages SET DEFAULT_VALUE = l_default_value, LAST_UPDATE_LOGIN = fnd_global.user_id, LAST_UPDATE_DATE = sysdate WHERE descriptive_flexfield_name = ‘$SRS$.’”rec.conc_program_name AND END_USER_COLUMN_NAME= rec.param_name AND DEFAULT_VALUE <> l_default_value;
fnd_file.put_line(fnd_file.LOG,rec.conc_program_name”‘,’”rec.param_name”‘,’”l_default_value”‘,’”SQL%ROWCOUNT); IF (SQL%ROWCOUNT > 0 ) THEN l_status := ‘Updated’; ELSE l_status := ‘Not Updated’; END IF; EXCEPTION WHEN others THEN l_status := sqlerrm; END; END IF;
fnd_file.put_line(fnd_file.output,rpad(rec.conc_program_name,20,‘ ‘)”‘ ‘”rpad(rec.param_name,30,‘ ‘)”‘ ‘”rpad(rec.old_default_value,70)”‘ ‘”rpad(l_default_value,70,‘ ‘)”‘ ‘”l_status); END LOOP;
IF (l_report_only <> ‘Yes’) THEN commit; END IF; EXCEPTION WHEN OTHERS THEN fnd_file.put_line(fnd_file.LOG,‘Error occurred while executing: ‘ ” SUBSTR(SQLERRM, 1, 150));END;/
Simple Query to find FND_LOOKUP Values. Oracle Applications – Simple Query to find FND_LOOKUP Values.
SELECT B.ROWID ROW_ID, B.APPLICATION_ID, B.LOOKUP_TYPE, B.CUSTOMIZATION_LEVEL, B.CREATED_BY, B.CREATION_DATE, B.LAST_UPDATED_BY, B.LAST_UPDATE_DATE, B.LAST_UPDATE_LOGIN, B.SECURITY_GROUP_ID, B.VIEW_APPLICATION_ID, T.MEANING, T.DESCRIPTIONFROM FND_LOOKUP_TYPES_TL T, FND_LOOKUP_TYPES BWHERE B.LOOKUP_TYPE = T.LOOKUP_TYPEAND B.SECURITY_GROUP_ID = T.SECURITY_GROUP_IDAND B.VIEW_APPLICATION_ID = T.VIEW_APPLICATION_IDAND T.LANGUAGE = userenv(‘LANG’)AND T.DESCRIPTION LIKE ‘%Capture%’
With parameter passing
SELECT B.ROWID ROW_ID, B.APPLICATION_ID, B.LOOKUP_TYPE, B.CUSTOMIZATION_LEVEL, B.CREATED_BY, B.CREATION_DATE, B.LAST_UPDATED_BY, B.LAST_UPDATE_DATE, B.LAST_UPDATE_LOGIN, B.SECURITY_GROUP_ID, B.VIEW_APPLICATION_ID, T.MEANING, T.DESCRIPTIONFROM FND_LOOKUP_TYPES_TL T, FND_LOOKUP_TYPES BWHERE B.LOOKUP_TYPE = T.LOOKUP_TYPE
AND B.SECURITY_GROUP_ID = T.SECURITY_GROUP_IDAND B.VIEW_APPLICATION_ID = T.VIEW_APPLICATION_IDAND T.LANGUAGE = userenv(‘LANG’)AND T.DESCRIPTION LIKE ‘%&&INPUT%’
Sample Script to Debug the Procedure, Packages Running At Backend For mission critical operations with big – complex PLSQL packages, we may need to know the path or the way the data is processed. In such case, it is very hard to debug the flow. I had such situation many times and it is easy to implement a simple solution using a debug log table for future review purpose. Make sure you delete or purge the table often and also create a proper index on this table to avoid performance issues later. This procedure can be global or inside a package. With oracle applications, you can have an entry in FND_LOOKUP_VALUES so that you can enable or disable debug on the fly by setting the lookup_type ( = ‘ERROR MESSAGE’).
Here is the sample code that I have used to capture online payment system. This is very handy and useful especially for direct online payment system to debug the unauthorized credit or system generated credit cards.
/*
Author:
Expecting a table like this: Hence, you may need to create the table before compiling this procedure
create table XXCUS_ERROR_LOG ( log_time date, Program_step number, Calling_Routine varchar2(255), Program_Message varchar2(255), ATTRIBUTE1 varchar2(255), ATTRIBUTE2 varchar2(255), ATTRIBUTE3 varchar2(255))
*/
PROCEDURE XXCUS_ERROR_PRC( PROGRAM_STEP VARCHAR2, ,CALLING_ROUTINE VARCHAR2 ,PROGRAM_MESSAGE VARCHAR2 ,ATTRIBUTE1 VARCHAR2 – ERROR INDICATOR ,ATTRIBUTE2 VARCHAR2 – ERROR MESSAGE ,ATTRIBUTE3 VARCHAR2) – LOCATION/SUCCESS/FAILIS PRAGMA AUTONOMOUS_TRANSACTION; l_log_enable_flag VARCHAR2(1) := ‘N’;BEGIN BEGIN SELECT ENABLED_FLAG INTO l_log_enable_flag FROM FND_LOOKUP_VALUES WHERE lookup_type = ‘ERROR MESSAGE’; EXCEPTION WHEN NO_DATA_FOUND THEN l_log_enable_flag := ‘N’; END;
IF l_log_enable_flag = ‘Y’ THEN INSERT INTO XXCUS_ERROR_LOG VALUES(SYSDATE
,Program_Step ,Calling_Routine ,Program_Message ,ATTRIBUTE1 ,ATTRIBUTE2 ,ATTRIBUTE3); END IF; COMMIT;EXCEPTION WHEN OTHERS THEN NULL;END XXCUS_ERROR_PRC;
Usage sample
g_my_sql_code := 100; XXCUS_ERROR_PRC(g_my_sql_code,‘USER’,SYS_CONTEXT(‘USERENV’,‘CURRENT_USER’),NULL,NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 101; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_customer_number’,p_customer_number,NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 102; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_currency’,p_currency,NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 103; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_org_id’,to_char(p_org_id),NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 104; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_credit_Card_no’,encrypt_prc(p_credit_Card_no),NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 105; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_expiration_date’,to_char(p_expiration_date,‘DD-MON-YYYY’),NULL,p_customer_number”‘_’”v_tangible_id); g_my_sql_code := 106; XXCUS_ERROR_PRC(g_my_sql_code,‘Parameter’,‘p_payment_option’,p_payment_option,NULL,p_customer_number”‘_’”v_tangible_id);
Another SQL script to find the profile option values. Here is another script that reports Profile Options For Oracle Applications.
You can also Download a_profile_opt_r11i.sql here
rem rem File: a_profile_opt_R11i.sql rem DESC: Reports Profile Options FOR Oracle Applications rem WITH NOT NULL VALUES, groups BY Profile OPTION Name rem breaks BY SITE, RESPONSIBILITY, APPLICATION, USER rem Takes Parameter Name AS search string rem Allows you TO VIEW ALL possible VALUES FOR profile rem including SITE, RESPONSIBILITY, APPLICATION AND USER. rem This IS impossible IN Oracle Apps GUI mode rem clear col clear breaks SET pages 9000 SET LINES 132 SET verify off col pov format a45 word_wrapped heading "Profile Value" col lo format a5 heading "Level" col lov format a40 heading "Value" col pon noprint new_value n_pon
col upon noprint new_value n_upon col sda noprint new_value n_sda col eda noprint new_value n_eda col cd noprint new_value n_cd col cb noprint new_value n_cb col d format a78 word_wrapped noprint new_value n_d break ON pon skip page ttitle – "Creation Date: " n_cd " Created By: " n_cb – skip 1 – "Date Active From:" n_sda " To:" n_eda - skip 1 – "Profile Option Name: " n_pon – skip 1 – "User Profile Name: " n_upon - skip 1 – "Profile Description: " - skip 1 – n_d - SELECT lpad(fpo.profile_option_name,55) pon , lpad(fpot.user_profile_option_name,55) upon , fpot.description d , lpad(fpo.start_date_active,15) sda , lpad(fpo.end_date_active,15) eda , lpad(fpo.creation_date,15) cd , lpad(fu.user_name,20) cb , ‘Site’ lo , ‘SITE’ lov , fpov.profile_option_value pov FROM FND_PROFILE_OPTIONS_TL fpot , FND_PROFILE_OPTIONS fpo , FND_PROFILE_OPTION_VALUES fpov , FND_USER fu WHERE fpot.user_profile_option_name LIKE ‘&&profile_like’ AND fpot.profile_option_name = fpo.profile_option_name AND fpo.application_id = fpov.application_id AND fpo.profile_option_id = fpov.profile_option_id AND fpo.created_by = fu.user_id AND fpot.LANGUAGE = Userenv(‘Lang’) AND fpov.level_id = 10001 /* Site Level */ union ALL SELECT lpad(fpo.profile_option_name,55) pon , lpad(fpot.user_profile_option_name,55) upon , fpot.description d , lpad(fpo.start_date_active,15) sda , lpad(fpo.end_date_active,15) eda , lpad(fpo.creation_date,15) cd , lpad(fu.user_name,20) cb , ‘Apps’ lo , fa.application_name lov , fpov.profile_option_value pov FROM FND_PROFILE_OPTIONS_TL fpot , FND_PROFILE_OPTIONS fpo , FND_PROFILE_OPTION_VALUES fpov , FND_USER fu , FND_APPLICATION_TL fa WHERE fpot.user_profile_option_name LIKE ‘&&profile_like’ AND fpot.profile_option_name = fpo.profile_option_name AND fpo.profile_option_id = fpov.profile_option_id AND fpo.created_by = fu.user_id AND fpot.LANGUAGE = Userenv(‘Lang’) AND fpov.level_id = 10002 /* Application Level */ AND fpov.level_value = fa.application_id union ALL SELECT lpad(fpo.profile_option_name,55) pon , lpad(fpot.user_profile_option_name,55) upon , fpot.description d , lpad(fpo.start_date_active,15) sda , lpad(fpo.end_date_active,15) eda , lpad(fpo.creation_date,15) cd , lpad(fu.user_name,20) cb , ‘Resp’ lo , frt.responsibility_name lov , fpov.profile_option_value pov FROM FND_PROFILE_OPTIONS_TL fpot , FND_PROFILE_OPTIONS fpo , FND_PROFILE_OPTION_VALUES fpov , FND_USER fu
, FND_RESPONSIBILITY_TL frt WHERE fpot.user_profile_option_name LIKE ‘&&profile_like’ AND fpot.profile_option_name = fpo.profile_option_name AND fpo.profile_option_id = fpov.profile_option_id AND fpo.created_by = fu.user_id AND frt.LANGUAGE = Userenv(‘Lang’) AND fpot.LANGUAGE = Userenv(‘Lang’) AND fpov.level_id = 10003 /* Responsibility Level */ AND fpov.level_value = frt.responsibility_id AND fpov.level_value_application_id = frt.application_id union ALL SELECT lpad(fpo.profile_option_name,55) pon , lpad(fpot.user_profile_option_name,55) upon , fpot.description d , lpad(fpo.start_date_active,15) sda , lpad(fpo.end_date_active,15) eda , lpad(fpo.creation_date,15) cd , lpad(fu.user_name,20) cb , ‘User’ lo , fu2.user_name lov , fpov.profile_option_value pov FROM FND_PROFILE_OPTIONS_TL fpot , FND_PROFILE_OPTIONS fpo , FND_PROFILE_OPTION_VALUES fpov , FND_USER fu , FND_USER fu2 WHERE fpot.user_profile_option_name LIKE ‘&&profile_like’ AND fpot.profile_option_name = fpo.profile_option_name AND fpo.profile_option_id = fpov.profile_option_id AND fpo.created_by = fu.user_id AND fpov.level_id = 10004 /* User Level */ AND fpov.level_value = fu2.user_id AND fpot.LANGUAGE = Userenv(‘Lang’) ORDER BY upon, lo, lov / undefine profile_like ttitle off
How do I see the debug messages either in log file or output file in oracle applications?
When you register a concurrent programs, such plsql packages, you can display the debug outputs either at output file or log file or both depending on the api you use. There are two functions from fnd_file packages that can be used to display the debug messages.
fnd_file.put_line(FND_FILE.LOG,"This is logfile test");
fnd_file.put_line(FND_FILE.out,"This is output test");
How To Add Responsibility to USER using pl/sql? – Oracle Applications
If you have the Apps Password, its quite easy to create a FND_USER for yourself by using the API. I find this script very useful when development environment gets cloned from Production(that is when i do not have FND_USER in Production).
Please note that:-1. You will be allocated System Administrator by this script. Hence you can assign whatever responsibilities that you desire latter, after logging in.2. The password will be set to oracle
3. You need apps password to run this script. Alternately you need execute permission on fnd_user_pkg from the user where this script will be run. If using some other user, please use apps.fnd_user_pkg.createuser4. You need a COMMIT. I have not included the commit within this script.5. When running this script, you will be prompted to enter a user name.
Using the pl/sql you can add responsibility to any USER without having Application System Administrator Rights.First, get value for ‘Responsablity_Application_Short_Name’ and ‘Responsibility_Key’ Parameters you need to run following sql Statement by Using APPS User Name
SELECT FAV.APPLICATION_SHORT_NAME, FAV.APPLICATION_NAME,FRV.RESPONSIBILITY_KEY, FRV.RESPONSIBILITY_NAMEFROM FND_APPLICATION_VL FAV, FND_RESPONSIBILITY_VL FRVWHERE FRV.APPLICATION_ID=FAV.APPLICATION_IDORDER BY FRV.RESPONSIBILITY_NAME
To add Responsibility of “Receivables Manager” to User
BEGIN fnd_user_pkg.addresp (‘’,‘AR’,‘RECEIVABLES_MANAGER’,‘STANDARD’,‘Add Responsibility to USER using pl/sql’,SYSDATE,SYSDATE + 100); COMMIT; DBMS_OUTPUT.put_line (‘Responsibility Added Successfully’);EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line ( ‘ Responsibility is not added due to ‘” SQLCODE” SUBSTR (SQLERRM, 1, 100)); ROLLBACK;END;
Another sample script to add System Administrator
DECLAREv_session_id INTEGER := userenv(’sessionid’);v_user_name VARCHAR2(30) := upper(‘&Enter_User_Name’);BEGIN–Note, can be executed only when you have apps password.– Call the procedure to Creaet FND Userfnd_user_pkg.createuser(x_user_name => v_user_name,x_owner => ”,x_unencrypted_password => ‘oracle’,x_session_number => v_session_id,x_start_date => SYSDATE – 10,x_end_date => SYSDATE + 100,x_last_logon_date => SYSDATE – 10,x_description => ‘www.notesbit.com’,x_password_date => SYSDATE – 10,x_password_accesses_left => 10000,x_password_lifespan_accesses => 10000,x_password_lifespan_days => 10000,x_employee_id => 30 /*Change this id by running below SQL*//*SELECT person_id,full_nameFROM per_all_people_f
WHERE upper(full_name) LIKE ‘%’ ” upper(’full_name’) ” ‘%’GROUP BY person_id,full_name*/,x_email_address => ‘[email protected]’,x_fax => ”,x_customer_id => ”,x_supplier_id => ”);fnd_user_pkg.addresp(username => v_user_name,resp_app => ‘SYSADMIN’,resp_key => ‘SYSTEM_ADMINISTRATOR’,security_group => ‘STANDARD’,description => ‘Auto Assignment’,start_date => SYSDATE – 10,end_date => SYSDATE + 1000);END;/
Following are the reference for the pl/sql package
beginfnd_user_pkg.addresp( ‘&User_Name’, /*Application User Name */ ‘&Responsablity_Application_Short_Name’, /*get from Query Below */ ‘&Responsibility_Key’,/*get from Query Below */ ‘&Security_Group’, /* Most of cases it is ‘STANDARD’ so you can hard code it */ ‘&Description’, /* Any comments you want */ ‘&Start_Date’, /* Sysdate From Today */ ‘&End_Date’ ); /* Sysdate + 365 Rights for Next One Year*/commit;
dbms_output.put_line(‘Responsibility Added Successfully’);
exception when others then dbms_output.put_line(‘ Responsibility is not added due to ‘ ” SQLCODE ” substr(SQLERRM, 1, 100)); Rollback;end;/
Here Is A Sample Unix / Linux Script That Checks The Payment Settlement File And Acknowledgement File
I had an opportunity to work with Paymentech integration (oracle iPayment system) with oracle 11i aplications. Paymentech needs a settlement file from the source system, verifies all the transactions, and finally acknowledges back to the source with Acknowledgement Flag=”Y” at the end of each record. Unfortunately, the implementers did not follow the standard oracle practice and the system was not made with $XXCUS/ipayment/in, $XXCUS/ipayment/out and $XXCUS/ipayment/archive directories. Both settlement and acknowledgment files are located at the same place at $XXCUS/iPayment. During the course, it is hard to find whether the files are acknowledged or not. I wrote a simple UNIX / Linux shell script to identify the acknowledge file provide you give the settlement file. This is mainly used as debugging script.
The logic is take a record and find the unique portion (identity) of it from the source. Then using this grep all the files except the source file which contains the unique identity. If found, the source is acknowledge, else not acknowledge at the time of the program run. Finally it sends the not acknowledged source file listings by email to you.
#!/bin/sh## Developed by # notack = Not acknowledged #JFILE=$1FILENAME="notacksingle.txt"if [ -f $FILENAME ]then rm -rf $FILENAME echo "Old Data File ($FILENAME) deleted…"fiSRCDIR="$XXCUS/iPayment"FTITLE="Missing ftp files dated `date`"echo ${FTITLE} ‘ tee -a ${FILENAME}## 11665 is an exception, received by us#SRCLIST=`ls -C1 ${SRCDIR} ‘ grep -i ${JFILE} ‘ grep -v done` for ARG in $SRCLISTdo #echo "${SRCDIR}/${ARG}" VAR=`grep -i "^S" "${SRCDIR}/${ARG}" ‘ head -1 ‘ cut -b1-20` #echo $VAR #VAR=`cut -b1-20 "${SRCDIR}/${ARG}" ‘ head -2 ‘ tail -1 ` #echo "grep -i ${VAR} ${SRCDIR}/*done" RES=`grep -i ${VAR} ${SRCDIR}/*done` #echo "${RES}" if [ -z "${RES}" ]; then echo "`ls -ltr ${SRCDIR}/${ARG}` `tail -2 ${SRCDIR}/${ARG} ‘ head -1 ‘ cut -b59-72`" ‘ tee -a ${FILENAME} fidone#If the file size is greater than 52 char, it has real value: This may vary in your installationif [ -f $FILENAME ]then FILESIZE=$(stat -c%s "$FILENAME") if [ $FILESIZE -gt 52 ] then uuencode $FILENAME $FILENAME ‘ mail -s "${FTITLE}" "[email protected]" fifi
Steps To Register Shell Script As A Concurrent Program
Oracle Applications – How to register Forms or Reports? Unix / Linux Secure Copy (SCP) usage and syntax How do you Create soft link with ln command in Linux / UNIX?
Simple K-shell (Linux,UNIX) program to monitor concurrent programs and provide feedback.
Oracle Applications: The Concurrent Jobs Ran Yesterday and Failed – SQL script & Unix Shell Script
There are two methods to handle, one with symbolic link another without symbolic link.
step 1: Place the .prog script under the bin directory for your applications top directory.For example, call the script SHELLDEMO.prog and place it under $XXCUS/bin
step 2: Make a symbolic link from your script to $FND_TOP/bin/fndcpesrFor example, if the script is called SHELLDEMO.prog use this:
ln -s $FND_TOP/bin/fndcpesr SHELLDEMO
This link should be named the same as your script without the .prog extension.Put the link for your script in the same directory where the script is located.
step 3: Register the concurrent program, using an execution method of ‘Host’. Use the name of your script without the .prog extensionas the name of the executable.For the example above: Use SHELLDEMO
step 4: Your script will be passed at least 4 parameters, from $1 to $4.
$1 = orauser/pwd$2 = userid(apps)$3 = username,$4 = request_id
Any other parameters you define will be passed in as $5 and higher. Make sure your script returns an exit status also.Sample Shell Script: First method uses symbolic link.
#!/bin/sh#Note: If you see # in front of any line it means that its a comment line not the actual code# =========================================================# Script Name : SHELLDEMO.prog# Developed by # =========================================================#Parameters from 1 to 4 i.e $1 $2 $3 $4 are standard parameters# $1 : USERNAME/PASSWORD OF THE DATABASE# $2 : USERID# $3 : USERNAME# $4 : CONCURRENT REQUEST IDecho "_________________"echo "Parameters received from concurrent program .."echo " Time : "`date`echo "_________________"echo "Arguments : "
echo "user_name=$1"echo "_________________"echo " Logging to "
APPS_USER_PASS=$1
# Note the EOF must be placed after << and as First three char showing eod of file signal# It can be any char or phrase acceptable for shell programming
sqlplus -s $APPS_USER_PASS <<EOFselect sysdate from dual;EOFif [ $? -ne 0 ]# the $? will contain the result of previously executed statement.#It will be 0 if success and 1 if fail in many cases# -ne represents not "equal to"thenecho "Entered Exception"exit 1# exit 1 represents concurrent program status. 1 for error, 2 for warning 0 for successelseecho "File Successfully copied from source to destination"exit 0fi# =========================================================
Second Method does not use Symbolic Link.
#!/bin/sh#Note: If you see # in front of any line it means that its a comment line not the actual code# =========================================================# Script Name : SHELLDEMO.prog# Developed by # =========================================================echo "starting file"old_args=$1echo "old_args=$old_args"
APPS_USER_PASS=`echo $1 ‘ cut -d" " -f3 ‘ sed ’s/FCP_LOGIN=//g’ ‘ sed ‘s/"//g’`
# Note the EOF must be placed after << and as First three char showing eod of file signal# It can be any char or phrase acceptable for shell programming
sqlplus -s $APPS_USER_PASS <<EOFselect sysdate from dual;EOFif [ $? -ne 0 ]# the $? will contain the result of previously executed statement.#It will be 0 if success and 1 if fail in many cases# -ne represents not "equal to"thenecho "Entered Exception"exit 1# exit 1 represents concurrent program status. 1 for error, 2 for warning 0 for success
elseecho "File Successfully copied from source to destination"exit 0fi# =========================================================
GL Date Move for Lockbox Records – Oracle Applications tips – SQL
Few companies have streamlined their operations to avoid GL_Date move. Moving GL date is very common fix in many companies, especially during the month end activities. Here is one of the requirements in which we need to move the gl_date of the lockbox records before creating the lockbox records.
The lockbox data is sent by banks very late evening. In addition, loading errors and the records errors are being fixed at night. However, General ledger period will be closed by 12 midnight. Hence, we are forced to move the gl_date for the future or open period.
It is wise to take a backup of the two tables. You need to run this as apps user or any user which has the privilege to run these scripts.
CREATE TABLE ar_transmissions_all_tmp AS SELECT * FROM ar_transmissions_all;
CREATE TABLE ar_payments_interface_all_tmp AS SELECT * FROM ar_payments_interface_all;
If you know the transmission name:
SELECT transmission_id FROM ar_transmissions_all WHERE transmission_name = ‘&&transmission_name’;
SELECT * FROM apps.ar_payments_interface_allWHERE 1=1AND transmission_id = &&transmission_id;
UPDATE ar_payments_interface_allSET gl_date=to_date(‘&&Required_gl_date’,‘DD/MM/YYYY’), STATUS=NULLWHERE 1=1AND transmission_id = &&transmission_id;
If you know the request id:
UPDATE ar_payments_interface_allSET gl_date=to_date(‘&&Required_gl_date’,‘DD/MM/YYYY’), STATUS=NULLWHERE 1=1AND transmission_request_id = &&request_id;
Once you commit, you run the lockbox process, it loads the data with the required GL Date.
How to secure login with oracle SQL*Plus with a password On UNIX and Linux platforms.
Most of us sometimes start SQL * Plus with a password on UNIX and Linux platforms without knowing security threat.
For example, an application user connects SQL * Plus by passing username and password on Unix/Linux Server.
$ sqlplus apps/apps@proddb
Here the sqlplus command parameters are very much available for viewing by all operating system users on the same host computer; as a result, password entered on the command line could be exposed to other users, as below.
$ ps -efgrep sqlplusoracle 14490 2190 0 16:31:53 pts/5 0:00 sqlplus apps/apps@proddboracle 14493 14491 0 16:32:01 pts/5 0:00 grep sqlplus
So, there might be a chance for an intruder to know the user id and password, and can connect to the database using that credentials.
Then, following is the secure and best way of connecting SQL * Plus where the password is not exposed on the command line.
$ sqlplus apps@proddbEnter password: ****
Or, even not to expose the username and connecting string.
$ sqlplusEnter user-name: apps@proddbEnter password: ****
Or
$ sqlplus /nologSQL> connect apps@proddbEnter password: ****
And also, do not use the password while invoking Export/Import Utility using exp/imp command line, and for any other command line utilities which you think the password will be exposed to others.
On Microsoft Windows, the command recall feature (the Up arrow) remembers user input across command invocations.
For example, if you use the CONNECT APPS/password notation in SQL*Plus, exit, and then press the Up arrow to repeat the CONNECT command, the command recall feature discloses the connect string and shows the password. So, it is advice *NOT* to pass the password while connecting to SQL * Plus on windows as well.
Oracle Applications Schema Password Change Utility – (FNDCPASS) http://www.notesbit.com/index.php/author/admin/ 17 March, 2009 14,354 views
Changing passwords periodically helps ensure database security. Oracle Applications provides a command line utility, FNDCPASS, to set Oracle Applications schema passwords. In addition to changing the schema password in the database, this utility changes the password registered in Oracle Applications tables (FND Tables). This utility can also change Applications End User passwords.
FNDCPASS changes
Oracle Applications Database System Users (APPS, APPLSYS) Oracle Applications Product Schema Passwords (GL, AR, AP, etc,)
Oracle Applications End User Account Passwords (SYSADMIN, OPERATIONS etc)
Note: the utility, FNDCPASS, cannot be used for changing the database SYSTEM and SYS users. Only users that are registered in FND meta data tables need to be changed using FNDCPASS. Normally, the APPS database user password and APPLSYS password need to be the same. When changing the APPLSYS password using FNDCPASS, the APPS password is also changed.
Syntax of FNDCPASS command:
FNDCPASS logon 0 Y system/password mode username new_password
Where logon is username/password[@connect]System/password is password of the system account of that databaseMode is SYSTEM/USER/ORACLEUsername is the username where you want to change its passwordnew_password is the new password in unencrypted format
Example:
$ FNDCPASS apps/apps 0 Y system/manager SYSTEM APPLSYS WELCOME
$ FNDCPASS apps/apps 0 Y system/manager ORACLE GL GL1
$ FNDCPASS apps/apps 0 Y system/manager USER VISION WELCOME
Note: The FNDCPASS has a new mode, “ALLORACLE”, in which all Oracle Application schema passwords can be changed in one call. Apply the patch (Patch No# 4745998) to have this option, if not available currently with your Apps.
Syntax:
FNDCPASS 0 Y ALLORACLE
Example:
$ FNDCPASS apps/apps 0 Y system/manager ALLORACLE WELCOME
To change APPS/APPLSYS password, we need to give mode as SYSTEMTo change product schema passwords, i.e., GL, AP, AR, etc., we need to give mode as ORACLETo change end user passwords, i.e., SYSADMIN, OPERATIONS etc., we need give mode as USER
Note: Till 11.5.9 there is bug in FNDCPASS, which allows FNDCPASS to change APPS&APPLSYS passwords. Doing so will corrupt the data in FND meta data tables and cause to the application unusable. Because of that it is recommend taking backup of the tables FND_USER and FND_ORACLE_USERID before changing the passwords.
After changing the APPS/APPLSYS or APPLSYSPUB user, following extra manual steps needs to be done.
If you changed the APPS (and APPLSYS) password, update the password in these files:
iAS_TOP/Apache/modplsql/cfg/wdbsvr.app ORACLE_HOME/reports60/server/CGIcmd.dat
If you changed the APPLSYSPUB password, update the password in these files:
FND_TOP/resource/appsweb.cfg OA_HTML/bin/appsweb.cfg
FND_TOP/secure/HOSTNAME_DBNAME.dbc
Note: I would you suggest you to first try changing the passwords using FNDCPASS on your test Apps Instances, once you are done with this without any errors or issues then you can move this to production, and also request you to search in metalink for more information about FNDCPASS utility and it’s usage.
Note: With FNDCPASS you cannot decrypt the password, but can change the password only!
What is FNDLOAD and how to use it? Oracle Applications : Steps for Creating New Operating Unit in a multi org set up. Oracle applications – List all the concurrent Jobs ran by user.
Pending normal jobs running (oracle 11i) in oracle applications
Setting the Applications Context FND_GLOBAL.APPS_INITIALIZE in oracle applications.
Get Operating Unit & Legal Entity
FNDLOADwhen we are working in oracle application development/implementation project? The equally important AOL data Migration takes place necessary to synchronize the data across databases instance during installation and upgarde.
Using FNDLOAD can download data from an application entity into an editable text file, which can be uploaded to another database.The Conversion between database format and text file format is specified by a configuration file.What can be Done?
·It can be done following list
· Concurrent Programs, Executables· Request Groups, Request Sets· Profile Options· Key and Descriptive Flexfields· Menus and Responsibilities· Forms and Form Functions· Attachments· Messages· Value Sets and Values· Lookup Types· User Responsibilities· Printer Definitions· FND Dictionary· Help Configuration· Document Sequences· Concurrent Manager Schedules
Advantages when using FNDLOAD 1. Because downloaded data is stored in a text file, version administration is possible2. No learning curve. this is relief for developer/dbas3. Fully supported and recommended by Oracle4. Capture the migrations in a file and use it during installations(log file).5. Pin-point when something happened and where (database) easily6. AOL data migration process is now simplified!
Disadvantages1. Applications patching mechanisms use FNDLOAD heavily possibility of negative impact is not zero2. No validation against migrating database/instance sensitive data
The Syntax To use FNDLOAD, the following syntax is needed.FNDLOAD apps/appspwd 0 Y mode configfile datafile entity [parameter1.....]· The mode is either DOWNLOAD or UPLOAD.· The configfile is the file that Fndload needs to download on upload data.· T he data file is the output file, in which the downloaded data is written· The entity is the entity you want to download,·
Example of download:FNDLOADapps/pwd 0 Y DOWNLOAD ${FND_TOP}/patch/115/import/afcpprog.lct myfile.ldt \ PROGRAM CONCURRENT_PROGRAM_NAME= concurrent_program_short_name> APPLICATION_SHORT_NAME=application_short_name
Example of UploadFNDLOAD apps/pwd 0 Y UPLOAD ${FND_TOP}/patch/115/import/afcpprog.lct myfile.ldt – CUSTOM_MODE=FORCE undocumented parameter
Where is Config File Located· Configuration files with extension .lcto On Unix – all the configuration files are in $FND_TOP/patch/115/import directoryo On Unix Oracle also places the original configuration files in $FND_TOP/admin/import directory·Data files with extension .ldt· The configfiles (.lct) are delivered and maintained by Oracle· It has entity definitions, parent-child relationships and user input parameters identified by :NAMEoDownloading a parent automatically downloads all children – (Example) Concurrent Program download
Sample Script Code for these Objects :
1 – Printer StylesFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afcppstl.lct file_name.ldt STYLE PRINTER_STYLE_NAME=printer style name
2 – LookupsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/aflvmlu.lct file_name.ldt
FND_LOOKUP_TYPE APPLICATION_SHORT_NAME=prod LOOKUP_TYPE=lookup name
3 – Descriptive Flexfield with all of specific ContextsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afffload.lct file_name.ldt DESC_FLEX P_LEVEL=?COL_ALL:REF_ALL:CTX_ONE:SEG_ALL? APPLICATION_SHORT_NAME=prod DESCRIPTIVE_FLEXFIELD_NAME=desc flex name P_CONTEXT_CODE=context name
4 – Key Flexfield StructuresFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afffload.lct file_name.ldt KEY_FLEX P_LEVEL=?COL_ALL:FQL_ALL:SQL_ALL:STR_ONE:WFP_ALL:SHA_ALL:CVR_ALL:SEG_ALL? APPLICATION_SHORT_NAME=prod ID_FLEX_CODE=key flex code P_STRUCTURE_CODE=structure name
5 – Concurrent ProgramsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afcpprog.lct file_name.ldt PROGRAM APPLICATION_SHORT_NAME=prod CONCURRENT_PROGRAM_NAME=concurrent name
6 – Value SetsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afffload.lct file_name.ldt VALUE_SET FLEX_VALUE_SET_NAME=value set name
7 – Value Sets with valuesFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afffload.lct file_name.ldt VALUE_SET_VALUE FLEX_VALUE_SET_NAME=value set name
8 – Profile OptionsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afscprof.lct file_name.ldt PROFILE PROFILE_NAME=profile option APPLICATION_SHORT_NAME=prod
9 – Requset GroupFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afcpreqg.lct file_name.ldt
REQUEST_GROUP REQUEST_GROUP_NAME=request group APPLICATION_SHORT_NAME=prod
10 – Request SetsFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afcprset.lct file_name.ldt REQ_SET APPLICATION_SHORT_NAME=prod REQUEST_SET_NAME=request set
11 – ResponsibilitiesFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afscursp.lct file_name.ldt FND_RESPONSIBILITY RESP_KEY=responsibility
12 – MenusFNDLOAD apps/apps@seed115 O Y DOWNLOAD $FND_TOP/patch/115/import/afsload.lct file_name.ldt MENU MENU_NAME=menu_name
13 Forms/FunctionsFNDLOAD apps/apps@seed115 0 Y DOWNLOAD $FND_TOP/patch/115/import/affrmcus.lct file_name.ldt FND_FORM_CUSTOM_RULES The Upload syntax for all styles: FNDLOAD apps/apps@seed115 0 Y UPLOAD $FND_TOP/patch/115/import/affrmcus.lct file_name.ldt
14. User/ResponsibilitiesFNDLOAD apps/apps@seed115 0 Y DOWNLOAD @FND:patch/115/import/afscursp.lct file_name.ldt FND_USER Then UPLOAD FNDLOAD apps/apps@seed115 0 Y UPLOAD [UPLOAD_PARTIAL] @FND:patch/115/import/afscursp.lct file_name.ldt FND_USER []
Receipt On Account & Unapplied – SQL Query
A cash receipt is an applied receipt if it is associated with a customer number and an open invoice(s).
An unapplied receipt is a cash receipt that can be applied to a customer account if it is associated with a customer number but not associated with an invoice (that is, there is no invoice for the sale or the invoice number is unknown).
An on-account receipt (cash-in-advance) is:
* recorded to the customer account* applied against the invoice when the invoice is generated
An unidentified receipt is from an unknown source.
An Application Advice Form is required for any receipt labeled as unidentified.
Here is the simple query to find the On-Account and UnApplied amount for a customer.
SELECT NVL (SUM (DECODE ( ara.STATUS, ‘ACC’, -amount_applied, 0 )), 0), NVL (SUM (DECODE ( ara.STATUS, ‘UNAPP’, -amount_applied, 0 )), 0) FROM ar_receivable_applications_all ara, ar_cash_receipts_all acr WHERE ara.cash_receipt_id = acr.cash_receipt_id AND acr.customer_site_use_id = ‘&&site_use_id’ AND ARA.STATUS IN ( ‘ACC’, ‘UNAPP’ ) AND ara.confirmed_flag IS NULL GROUP BY acr.currency_code, acr.customer_site_use_id;
Total Credit related to a customer – sql query – Oracle Applications
What is the Credit Note for and when to use it ?
A Credit Note or Credit Memo is a document used to adjust or rectify errors made in a sales invoice which has already been processed and sent to a customer. If you have already sent an invoice to a customer but now need to provide a credit for that invoice, you would send them a Credit Note or Credit Memo. You can think of a credit note as a “negative invoice.”
Some examples of when you would use a Credit Note
* Unit price overcharged or over-billed : For example you issued an invoice for an item for $1100 when the correct price of the item should have been $1010 instead. Therefore you need to issue Credit Note to give a credit of $90 to your customer for the amount over-billed. View Sample* Goods short shipped : You invoiced a customer for 10 units of your product but only shipped 9 units to them by mistake. The customer then calls you to say that 9 units are okay and does not want the shortfall item at the moment. Therefore you need to issue a Credit Note to credit your customer for the
shortfall quantity of 1 unit. View Sample* Faulty goods returned or goods rejected by customer. You would issue a credit note for the goods returned to correct your Accounts Receivable and Inventory. View Sample* Product Wrongly Shipped : You wrongly invoiced and shipped Product A when the customer actually ordered Product B which may or may not be at a different price. To rectify this, you would then ship Product B together with a Credit Note for Product A and another invoice for product B. This will restore the inventory and Accounts Receivable in your books while billing the customer for the correct item and amount. Meanwhile the customer returns the incorrect Product A. View Sample* Discounts given after the invoice is issued: You sent an invoice for $1100. The customer then calls you asking for a discount and ask you to waive the $100 making the net invoice amount $1000. You agree to this in good faith. You would then issue a credit note for $100 to this customer to adjust for the discount given. View Sample* To Write-off Customer Short Payments : You send an invoice for say $2010. The customer sends you a short payment of $2000 only. You do not wish to recover the shortfall amount but your books indicate that $10 is still owing on this invoice. You can then issue a credit note of $10 to write-off the shortfall amount.
Here is the simple SQL script that gives the total credit for a customer in oracle applications.
SELECT NVL (SUM (apsa.amount_due_remaining), 0) FROM ar_payment_schedules_all apsa WHERE apsa.customer_site_use_id = ‘&&site_use_id’ AND apsa.CLASS = ‘CM’ AND apsa.STATUS = ‘OP’ GROUP BY apsa.invoice_currency_code, apsa.customer_site_use_id;
Tuning & Performance – Gather Statistics importance
Oracle performance tuning – Gather Statistics:
Here is the one issue: I have same script using two tables as given below, running in two databases. The data, table names, indexes and the select statements are same. One database the query is running fast and another query is slow.
SELECT MAS.site_use_id, MAS.currency, DET.customer_id FROM table_master MAS, table_detail DET WHERE MAS.attribute1 = :Value AND DET.pk_id = MAS.pk_id
AND MAS.site_use_id = DET.site_use_idORDER BY MAS.site_use_id, MAS.currency;
In one database the scan is full table scan and in other uses index perfectly.
Plan
SELECT STATEMENT CHOOSE Cost: 49 Bytes: 114 Cardinality: 16 SORT ORDER BY Cost: 49 Bytes: 114 Cardinality: 15 NESTED LOOPS Cost: 2 Bytes: 114 Cardinality: 12 TABLE ACCESS BY INDEX ROWID APPS.table_master Cost: 1 Bytes: 95 Cardinality: 11 INDEX RANGE SCAN NON-UNIQUE APPS.XXCFI_MAS_ATTR1_N2 Cost: 1 Cardinality: 14 TABLE ACCESS BY INDEX ROWID CCA.table_detail Cost: 1 Bytes: 19 Cardinality: 13 INDEX UNIQUE SCAN UNIQUE CCA.table_detail_U1 Cardinality: 1
Plan
SELECT STATEMENT CHOOSE Cost: 62 Bytes: 282 Cardinality: 66 SORT ORDER BY Cost: 62 Bytes: 282 Cardinality: 65 COUNT STOPKEY4 HASH JOIN Cost: 38 Bytes: 282 Cardinality: 62 TABLE ACCESS BY INDEX ROWID APPS.table_master Cost: 5 Bytes: 35,084 Cardinality: 1,2531 INDEX RANGE SCAN NON-UNIQUE APPS.XXCFI_MAS_ATTR1_N2 Cost: 4 Cardinality: 1,2533 TABLE ACCESS FULL CCA.table_detail Cost: 32 Bytes: 181,545 Cardinality: 9,555
Then, what is wrong? The possible reason may be due to gather_statistics & estimation.You need to use the following gather statistics periodically.
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_N1′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_N2′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_U1′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_U2′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘XXCUS_EXP_DTL_N1′, estimate_percent => 30);
Locks on oracle database & Oracle applications Processing. In a single-user database, the user can modify data in the database without concern for other users modifying the same data at the same time. However, in a multiuser database, the statements within multiple simultaneous transactions can update the same data. Transactions executing at the same time need to produce meaningful and consistent results. Therefore, control of data concurrency and data consistency is vital in a multiuser database.
* Data concurrency means that many users can access data at the same time.* Data consistency means that each user sees a consistent view of the data, including visible changes made by the user’s own transactions and transactions of other users.
In general, multiuser databases use some form of data locking to solve the problems associated with data concurrency, consistency, and integrity. Locks are mechanisms that prevent destructive interaction between transactions accessing the same resource.
How do we find locks?
DBA_DML_LOCKSDisplays a session if it is not waiting for a locked object but is holding a lock on an object for which another session is waiting.
col "O/SUser" FOR a10col OraUser FOR a20col Blocking FOR a12col ObjLocked FOR a15col sid FOR 99999999col pid FOR a8SELECT s.osuser "O/SUser", s.username "OraUser", s.sid "SID",s.serial# "Serial", s.process "PID", s.status "Status",l.name "ObjLocked",l.mode_held "Lock Held" FROM V$SESSION s,DBA_DML_LOCKS l,V$PROCESS pWHERE l.session_id = s.sid AND p.addr = s.paddr;
Just another way to find the locks
SELECT VLO.OS_USER_NAME “OS USERNAME”, VLO.ORACLE_USERNAME “DB USER”,VP.SPID “SPID”, AO.OWNER “OWNER”, AO.OBJECT_NAME “OBJECT LOCKED”,AO.OBJECT_TYPE,DECODE (VLO.LOCKED_MODE,1, ‘NO LOCK’,2, ‘ROW SHARE’,3, ‘ROW EXCLUSIVE’,4, ‘SHARE’,5, ‘SHARE ROW EXCL’,6, ‘EXCLUSIVE’,NULL) “MODE OF LOCK”,VS.STATUS “CURRENT STATUS”FROM V$LOCKED_OBJECT VLO, ALL_OBJECTS AO, V$SESSION VS, V$PROCESS VPWHERE VLO.OBJECT_ID = AO.OBJECT_ID
AND VS.STATUS <> ‘KILLED’AND VLO.SESSION_ID = VS.SIDAND VS.PADDR = VP.ADDR;
Just to find a raw sql on a table lock!
SELECT * FROM dba_dml_locks WHERE name LIKE ‘%RA_CUSTOMER_TRX_ALL%’
SESSION_ID OWNER NAME MODE_HELD MODE_REQUESTED LAST_CONVERT BLOCKING_OTHERS 365 AR RA_CUSTOMER_TRX_ALL Row-X (SX) None 5081 NOT Blocking 365 AR RA_CUST_TRX_LINE_SALESREPS_ALL Row-X (SX) None 5081 NOT Blocking 365 AR RA_CUST_TRX_LINE_GL_DIST_ALL Row-X (SX) None 5081 NOT Blocking
Another simple scripts to find sesion, serial for locks. locks.sql displays all sessions holding a lock on a table or row.Knowing the session/serial#, you can kill some sessions unwanted for you!
SET term ON; SET LINES 130; COLUMN sid_ser format a12 heading ’session,’serial#’; COLUMN username format a12 heading ‘os user/’db user‘; column process format a9 heading ‘os‘process’; COLUMN spid format a7 heading ‘trace’number‘; column owner_object format a35 heading ‘owner.object‘; column locked_mode format a13 heading ‘locked‘mode’; COLUMN STATUS format a8 heading ’status’; spool locks.lst; SELECT substr(to_char(l.session_id)”‘,’”to_char(s.serial#),1,12) sid_ser, substr(l.os_user_name”‘/’”l.oracle_username,1,12) username, l.process, p.spid, substr(o.owner”‘.’”o.object_name,1,35) owner_object, decode(l.locked_mode, 1,‘No Lock’, 2,‘Row Share’, 3,‘Row Exclusive’, 4,‘Share’, 5,‘Share Row Excl’, 6,‘Exclusive’,NULL) locked_mode, substr(s.STATUS,1,8) STATUS FROM v$locked_object l, all_objects o, v$session s, v$process p WHERE l.object_id = o.object_id AND l.session_id = s.sid AND s.paddr = p.addr
AND s.STATUS != ‘KILLED’; spool off;
This produces an output like this
session, os user/ os trace locked serial# db user process number owner.object mode status ———— ———— ——— ——- ———————————– ————- ——– 81,47000 oadv1qtc/APP 23844 APPS.JTF_FM_RAPID_M_QTBL Row Exclusive ACTIVE 239,31 oadv1qtc/APP 2455 27900 APPLSYS.FND_CONCURRENT_QUEUES Row Exclusive INACTIVE 498,1 oadv1qtc/APP 28452 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_I Row Exclusive ACTIVE 512,6 oadv1qtc/APP 28484 APPLSYS.AQ$_FND_CP_GSM_OPP_AQTBL_I Row Exclusive ACTIVE 498,1 oadv1qtc/APP 28452 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_H Row Exclusive ACTIVE 577,29592 oadv1qtc/APP 23268 APPS.JTF_FM_RAPID_RS_QTBL Row Exclusive ACTIVE 498,1 oadv1qtc/APP 28452 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_T Row Exclusive ACTIVE 500,6 oadv1qtc/APP 28456 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_I Row Exclusive ACTIVE 236,27 oadv1qtc/APP 27822 APPS.JTF_FM_RAPID_B_QTBL Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_XXIBE_CUST_CON_ROLES_ST_I Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_XXIBE_CUST_CON_ROLES_ST_H Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_XXIBE_CUST_CON_ROLES_ST_T Row Exclusive ACTIVE 179,2063 oadv1qtc/APP 11261 4449 CMF.XXCMF_ATP_LINES_ARCHIVE Row Exclusive INACTIVE 500,6 oadv1qtc/APP 28456 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_H Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_SO_LINES_ALL11_ST_I Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_SO_LINES_ALL11_ST_H Row Exclusive ACTIVE 536,55348 oadv1qtc/APP 16323 APPS.JTF_FM_RAPID_RQ_QTBL Row Exclusive ACTIVE 557,3240 /AQADM 26352 AQADM.AQ$_SO_LINES_ALL11_ST_T Row Exclusive ACTIVE 500,6 oadv1qtc/APP 28456 APPLSYS.AQ$_FND_CP_GSM_IPC_AQTBL_T Row Exclusive ACTIVE 19,112 oadv1qtc/APP 2007 27500 APPLSYS.FND_CONCURRENT_REQUESTS Row Exclusive INACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_OE_CMRS_INCR_CUST_ST_I Row Exclusive ACTIVE 512,6 oadv1qtc/APP 28484 APPLSYS.AQ$_FND_CP_GSM_OPP_AQTBL_H Row Exclusive ACTIVE
512,6 oadv1qtc/APP 28484 APPLSYS.AQ$_FND_CP_GSM_OPP_AQTBL_T Row Exclusive ACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_OE_CMRS_INCR_CUST_ST_H Row Exclusive ACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_OE_CMRS_INCR_CUST_ST_T Row Exclusive ACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_CCAXB11_ST_I Row Exclusive ACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_CCAXB11_ST_H Row Exclusive ACTIVE 106,6631 /AQADM 26368 AQADM.AQ$_CCAXB11_ST_T Row Exclusive ACTIVE 207,185 oadv1qtc/APP 27763 APPS.JTF_FM_RAPID_RQ_QTBL Row Exclusive ACTIVE 549,13404 oadv1qtc/APP 21933 15264 GESADM.MLOG$_XXCMF_ATP_LINES_ARCHIV Row Exclusive INACTIVE 179,2063 oadv1qtc/APP 11261 4449 GESADM.MLOG$_XXCMF_ATP_LINES_ARCHIV Row Exclusive INACTIVE 549,13404 oadv1qtc/APP 21933 15264 CMF.XXCMF_ATP_LINES_ARCHIVE Row Exclusive INACTIVE 179,2063 oadv1qtc/APP 11261 4449 CMF.XXCMF_ATP_HEADERS_ARCHIVE Row Exclusive INACTIVE 549,13404 oadv1qtc/APP 21933 15264 CMF.XXCMF_ATP_HEADERS_ARCHIVE Row Exclusive INACTIVE 90,4133 oadv1qtc/APP 11987 4953 GESADM.MLOG$_XXCMF_ATP_LINES_ARCHIV Row Exclusive INACTIVE 90,4133 oadv1qtc/APP 11987 4953 CMF.XXCMF_ATP_HEADERS_ARCHIVE Row Exclusive INACTIVE 90,4133 oadv1qtc/APP 11987 4953 CMF.XXCMF_ATP_LINES_ARCHIVE Row Exclusive INACTIVE
37 rows selected.
Yet another script that gives more locks information
SELECT /*+ ordered */ –b.kaddr, c.sid, lock_waiter.waiting_session, lock_blocker.holding_session, c.program, c.osuser, c.machine, c.process, decode(u.name, NULL,”, u.name”‘.’”o.name ) object, c.username, decode ( b.type, ‘BL’, ‘Buffer hash table instance lock’, ‘CF’, ‘Control file schema global enqueue lock’, ‘CI’, ‘Cross-instance function invocation instance lock’,
‘CU’, ‘Cursor bind lock’, ‘DF’, ‘Data file instance lock’, ‘DL’, ‘direct loader parallel index create lock’, ‘DM’, ‘Mount/startup db primary/secondary instance lock’, ‘DR’, ‘Distributed recovery process lock’, ‘DX’, ‘Distributed transaction entry lock’, ‘FS’, ‘File set lock’, ‘IN’, ‘Instance number lock’, ‘IR’, ‘Instance recovery serialization global enqueue lock’, ‘IS’, ‘Instance state lock’, ‘IV’, ‘Library cache invalidation instance lock’, ‘JQ’, ‘Job queue lock’, ‘KK’, ‘Thread kick lock’, ‘LA’,‘Library cache lock instance lock (A..P=namespace);’, ‘LB’,‘Library cache lock instance lock (A..P=namespace);’, ‘LC’,‘Library cache lock instance lock (A..P=namespace);’, ‘LD’,‘Library cache lock instance lock (A..P=namespace);’, ‘LE’,‘Library cache lock instance lock (A..P=namespace);’, ‘LF’,‘Library cache lock instance lock (A..P=namespace);’, ‘LG’,‘Library cache lock instance lock (A..P=namespace);’, ‘LH’,‘Library cache lock instance lock (A..P=namespace);’, ‘LI’,‘Library cache lock instance lock (A..P=namespace);’, ‘LJ’,‘Library cache lock instance lock (A..P=namespace);’, ‘LK’,‘Library cache lock instance lock (A..P=namespace);’, ‘LL’,‘Library cache lock instance lock (A..P=namespace);’, ‘LM’,‘Library cache lock instance lock (A..P=namespace);’, ‘LN’,‘Library cache lock instance lock (A..P=namespace);’, ‘LO’,‘Library cache lock instance lock (A..P=namespace);’, ‘LP’,‘Library cache lock instance lock (A..P=namespace);’, ‘MM’, ‘Mount definition global enqueue lock’, ‘MR’, ‘Media recovery lock’, ‘NA’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NB’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NC’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘ND’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NE’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NF’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NG’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NH’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NI’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NJ’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NK’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NL’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NM’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NN’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NO’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NP’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NQ’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NR’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NS’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NT’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NU’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NV’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NW’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NX’, ‘Library cache pin instance lock (A..Z=namespace)’,
‘NY’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘NZ’, ‘Library cache pin instance lock (A..Z=namespace)’, ‘PF’, ‘Password File lock’, ‘PI’, ‘Parallel operation locks’, ‘PS’, ‘Parallel operation locks’, ‘PR’, ‘Process startup lock’, ‘QA’,‘Row cache instance lock (A..Z=cache)’, ‘QB’,‘Row cache instance lock (A..Z=cache)’, ‘QC’,‘Row cache instance lock (A..Z=cache)’, ‘QD’,‘Row cache instance lock (A..Z=cache)’, ‘QE’,‘Row cache instance lock (A..Z=cache)’, ‘QF’,‘Row cache instance lock (A..Z=cache)’, ‘QG’,‘Row cache instance lock (A..Z=cache)’, ‘QH’,‘Row cache instance lock (A..Z=cache)’, ‘QI’,‘Row cache instance lock (A..Z=cache)’, ‘QJ’,‘Row cache instance lock (A..Z=cache)’, ‘QK’,‘Row cache instance lock (A..Z=cache)’, ‘QL’,‘Row cache instance lock (A..Z=cache)’, ‘QM’,‘Row cache instance lock (A..Z=cache)’, ‘QN’,‘Row cache instance lock (A..Z=cache)’, ‘QP’,‘Row cache instance lock (A..Z=cache)’, ‘QQ’,‘Row cache instance lock (A..Z=cache)’, ‘QR’,‘Row cache instance lock (A..Z=cache)’, ‘QS’,‘Row cache instance lock (A..Z=cache)’, ‘QT’,‘Row cache instance lock (A..Z=cache)’, ‘QU’,‘Row cache instance lock (A..Z=cache)’, ‘QV’,‘Row cache instance lock (A..Z=cache)’, ‘QW’,‘Row cache instance lock (A..Z=cache)’, ‘QX’,‘Row cache instance lock (A..Z=cache)’, ‘QY’,‘Row cache instance lock (A..Z=cache)’, ‘QZ’,‘Row cache instance lock (A..Z=cache)’, ‘RT’, ‘Redo thread global enqueue lock’, ‘SC’, ‘System commit number instance lock’, ‘SM’, ‘SMON lock’, ‘SN’, ‘Sequence number instance lock’, ‘SQ’, ‘Sequence number enqueue lock’, ‘SS’, ‘Sort segment locks’, ‘ST’, ‘Space transaction enqueue lock’, ‘SV’, ‘Sequence number value lock’, ‘TA’, ‘Generic enqueue lock’, ‘TS’, ‘Temporary segment enqueue lock (ID2=0)’, ‘TS’, ‘New block allocation enqueue lock (ID2=1)’, ‘TT’, ‘Temporary table enqueue lock’, ‘UN’, ‘User name lock’, ‘US’, ‘Undo segment DDL lock’, ‘WL’, ‘Being-written redo log instance lock’, b.type ) lock_type, decode ( b.lmode, 0, ‘None’, /* Mon Lock equivalent */ 1, ‘Null’, /* N */ 2, ‘Row-S (SS)’, /* L */ 3, ‘Row-X (SX)’, /* R */
4, ‘Share’, /* S */ 5, ‘S/Row-X (SRX)’, /* C */ 6, ‘Exclusive’, /* X */ to_char(b.lmode) ) mode_held, decode ( b.request, 0, ‘None’, /* Mon Lock equivalent */ 1, ‘Null’, /* N */ 2, ‘Row-S (SS)’, /* L */ 3, ‘Row-X (SX)’, /* R */ 4, ‘Share’, /* S */ 5, ‘S/Row-X (SSX)’, /* C */ 6, ‘Exclusive’, /* X */ to_char(b.request) ) mode_requestedFROM v$lock b ,v$session c ,sys.user$ u ,sys.obj$ o ,( SELECT * FROM sys.dba_waiters) lock_blocker ,( SELECT * FROM sys.dba_waiters) lock_waiterWHEREb.sid = c.sidAND u.user# = c.user#AND o.obj#(+) = b.id1AND lock_blocker.waiting_session(+) = c.sidAND lock_waiter.holding_session(+) = c.sidAND c.username != ‘SYS’ORDER BY kaddr, lockwait;
FND_GLOBAL: WHO Column Maintenance and Database Initialization – Oracle Applications
The server-side package FND_GLOBAL returns the values of system globals, such as the login/signon or “session” type of values. You need to set Who columns for inserts and updates from stored procedures. Although you can use the FND_GLOBAL package for various purposes, setting Who columns is the package’s primary use.
You should not use FND_GLOBAL routines in your forms (that is on the client side), as FND_GLOBAL routines are stored procedures in the database and would cause extra roundtrips to the database. On the client side, most of the procedures in the FND_GLOBAL package are replaced by a user profile option with the same (or a similar) name. You should use FND_PROFILE routines in your forms instead.
Following are the FND_GLOBAL functions/Procedures
FND_GLOBAL.USER_ID;
FND_GLOBAL.APPS_INITIALIZE(user_id IN number, resp_id IN number, resp_appl_id IN number);
FND_GLOBAL.LOGIN_ID;
FND_GLOBAL.CONC_LOGIN_ID;
FND_GLOBAL.PROG_APPL_ID;
FND_GLOBAL.CONC_PROGRAM_ID ;
FND_GLOBAL.CONC_REQUEST_ID
How do you check the profile option values using sql – Oracle Applications?
Profile Options provide flexibility to Oracle Apps. They are a key component of Oracle Applications, hence these much be understood properly. I will be taking multiple examples here to explain what profile options mean. I will also try to explain by stepping into Oracle shoes “How will you design a program that is flexible”, by using Profile Options. These are provided to keep the application flexible. The business rules in various countries and various companies can be different. Hence the profile options are delivered by Oracle in such a manner to avoid hard-coding of logic, and to let the implementation team at site decide the values of those variables
This simple sql will provide you the profile option value for an user in oracle applications. You can modify the query easily to get site level, responsibility level profile option check.
Assumption: User name and profile partial or full input required for this user level profile option value listing query.
SELECT po.profile_option_name "NAME",po.USER_PROFILE_OPTION_NAME, decode(to_char(pov.level_id), ‘10001′, ‘SITE’, ‘10002′, ‘APP’, ‘10003′, ‘RESP’, ‘10005′, ‘SERVER’, ‘10006′, ‘ORG’, ‘10004′, ‘USER’, ‘???’) "LEV", decode(to_char(pov.level_id), ‘10001′, ”, ‘10002′, app.application_short_name, ‘10003′, rsp.responsibility_key, ‘10005′, svr.node_name, ‘10006′, org.name, ‘10004′, usr.user_name,
‘???’) "CONTEXT", pov.profile_option_value "VALUE" FROM FND_PROFILE_OPTIONS_VL po, FND_PROFILE_OPTION_VALUES pov, fnd_user usr, fnd_application app, fnd_responsibility rsp, fnd_nodes svr, hr_operating_units org WHERE po.profile_option_name LIKE ‘%&&profile%’ AND pov.application_id = po.application_id AND pov.profile_option_id = po.profile_option_id AND usr.user_id (+) = pov.level_value AND rsp.application_id (+) = pov.level_value_application_id AND rsp.responsibility_id (+) = pov.level_value AND app.application_id (+) = pov.level_value AND svr.node_id (+) = pov.level_value AND org.organization_id (+) = pov.level_value AND decode(to_char(pov.level_id), ‘10001′, ”, ‘10002′, app.application_short_name, ‘10003′, rsp.responsibility_key, ‘10005′, svr.node_name, ‘10006′, org.name, ‘10004′, usr.user_name, ‘???’) LIKE ‘%&&username%’ ORDER BY "NAME", pov.level_id, "VALUE";
How to check the user level in oracle? 10004 level_id shows user level profile option.
Column Description
Profile LevelLevel 1 = Site ( level_id=10001)Level 2 = Application ( level_id=10002)
Level 3 = Responsibility ( level_id=10003)Level 4 = User ( level_id=10004)
Site In case of site level value, it has the value ‘SITE’
Application Level In case of application level value, it has the name of the application
Responsibility Level
In case of responsibility level value, it has the name of the responsibility
User Level In case of user level value, it has the name of the user
Profile Name Profile Option name
Profile Option Value Value of the Profile Option
Source Module Related source module. E.g. ADI profile options belong to General Ledger module
Last Update Date Last update date
Update By User name who performed the last update
How can we find the receipts related to a transmission?
Every lockbox loading has a transmission name in oracle applications.How can we find the receipts stuck or related to a transmission if they stored in interface?Note: If you have setup to purge/delete the interface records after successful receipts, you may not get the receipts with this query.
SELECT transmission_id FROM Ar_transmissions_all WHERE transmission_name =‘wirep.05041908361_1′; – transmissionName is wirep.05041908361_1
SELECT * FROM AR_PAYMENTS_INTERFACE WHERE transmission_id IN ( SELECT transmission_id FROM Ar_transmissions_all WHERE transmission_name =‘wirep.05041908361_1′); – transmissionName is wirep.05041908361_1
Receipt API in Oracle Receivables
Autolock box provides a functionality to create receipts using interface method. Recent versions of oracle applications, especially 11.5 onwards, Receipt API is getting used as they are flexible to the user’s need, and customization across all kinds of interfaces, loading.
Here are the receipt APIs used in 11i applications:
ar_receipt_api_pub.Create_cashar_receipt_api_pub.Applyar_receipt_api_pub.Unapplyar_receipt_api_pub.Reversear_receipt_api_pub.Apply_on_accountar_receipt_api_pub.Unapply_on_accountar_receipt_api_pub.Activity_applicationar_receipt_api_pub.Activity_unapplicationar_receipt_api_pub.Apply_other_account
ar_receipt_api_pub.Unapply_other_accountar_receipt_api_pub.create_miscar_receipt_api_pub.set_profile_for_testingar_receipt_api_pub.Apply_Open_Receiptar_receipt_api_pub.Unapply_Open_Receipt
I will soon add more with usage of receipt APIs..
Find responsibilities associated with the users – using sql Following sql will help you find the responsibilities associated with the users in oracle applications.
SELECT frt.RESPONSIBILITY_NAME, furg.end_dateFROM fnd_user_resp_groups furg, FND_RESPONSIBILITY fr, fnd_responsibility_tl frt, fnd_user fuWHERE fu.user_name = ‘&&username’AND fu.user_id = furg.user_idAND furg.responsibility_id = fr.RESPONSIBILITY_IDAND frt.responsibility_id = fr.RESPONSIBILITY_IDORDER BY 1
How to run a unix host command from oracle plsql package? http://www.notesbit.com/index.php/author/admin/ 16 February, 2009 24,056 views
Often you will come across a situation in which you need to execute unix commands from plsql packages. If a simple utility exists to run unix command within plsql that simplifies your life instead of changing the design or finding an alternate approach to meet the goal. Oracle has provided a utility dbms_pipe run the UNIX host command from sql, plsql.
Here are the sample script to run the host_command.
SELECT apps.host_command(‘ls -ltr’) FROM dual
SELECT apps.host_command(‘chmod 777 /devel/appl/xxcus/1.0.0/bin/filename’) FROM dual
CREATE OR REPLACE FUNCTION host_command( cmd IN VARCHAR2 ) RETURN INTEGER IS STATUS NUMBER; errormsg VARCHAR2(80); pipe_name VARCHAR2(30);BEGIN pipe_name := ‘HOST_PIPE’; dbms_pipe.pack_message( cmd );
STATUS := dbms_pipe.send_message(pipe_name); RETURN STATUS;END;/
Validate the credit card (oracle 10 g plsql code) – working! The Luhn algorithm or Luhn formula, also known as the “modulus 10″ or “mod 10″ algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.
Recently, Oracle has stopped validating the credit card numbers as there is match for Authorization of credit card. However, this rudimentary mod-10 LUHN algorithm is still valid and valuable for us to check.
Hence, I started creating this mod-10 LUHN algorithm in plsql. This is tested with oracle 10 g database and working well. Special Thanks to ashish who has fixed the bug and tested the code.
Download the credit_card_validator.zip
–===========================================================================– Copyright 2008 Author:–=============================================================================– DESCRIPTION– I have been searching for a plsql package to validate the credit card.– Eventhough I created a Visual C# program to validate credit card,– I was lazy enough to create a plsql. Finally, here you go with LUHN!–=============================================================================–– table indicates card type, prefix, length and also for known cards—————-– CARD TYPE………………..Prefix………Length..Check digit algorithm– MASTERCARD……………….51-55……….16……mod 10 – VISA…………………….4…………..13,16…mod 10 – AMEX…………………….34,37……….15……mod 10 – Diners Club………………300-305,36,38..14……mod 10 – Discover…………………6011………..16……mod 10 – enRoute………………….2014,2149……15……any – JCB……………………..3…………..16……mod 10 – JCB……………………..2131,1800……15……mod 10 –===========================================================================––VALIDATECREDITCARD(’371536720471006′)–
CREATE OR REPLACE FUNCTION validatecreditcard (p_creditcardnumber IN VARCHAR2) RETURN VARCHAR2IS creditcardnumber VARCHAR2 (32); – := nosymbols (p_CreditCardNumber, LENGTH (p_CreditCardNumber)); creditcardlength NUMBER := LENGTH (p_creditcardnumber);
subtotal NUMBER := 0; t_value NUMBER := 0; c1 NUMBER; c2 NUMBER; c3 NUMBER; c4 NUMBER; cardtype VARCHAR2 (160) := ‘CARD’; calculationmethod VARCHAR2 (160) := ‘UNKNOWN’; RESULT VARCHAR2 (160);BEGIN creditcardnumber := LTRIM(RTRIM(p_creditcardnumber)); creditcardnumber := REPLACE(creditcardnumber, ‘-’, ”); creditcardnumber := REPLACE(creditcardnumber, ‘.’, ”); –IF isnumber (CreditCardNumber) = 0 THEN
c1 := TO_NUMBER (SUBSTR (creditcardnumber, 1, 1)); c2 := TO_NUMBER (SUBSTR (creditcardnumber, 1, 2)); c3 := TO_NUMBER (SUBSTR (creditcardnumber, 1, 3)); c4 := TO_NUMBER (SUBSTR (creditcardnumber, 1, 4));
IF creditcardlength = 13 THEN IF c1 IN (4) THEN cardtype := ‘VISA’; calculationmethod := ‘MOD10′; END IF; ELSIF creditcardlength = 14 THEN IF c2 IN (36, 38) THEN cardtype := ‘DINERS CLUB’; calculationmethod := ‘MOD10′; ELSIF c3 IN (300, 301, 302, 303, 304, 305) THEN cardtype := ‘DINERS CLUB’; calculationmethod := ‘MOD10′; END IF; ELSIF creditcardlength = 15 THEN IF c2 IN (34, 37) THEN cardtype := ‘AMEX’; calculationmethod := ‘MOD10′; ELSIF c4 IN (2014, 2149) THEN cardtype := ‘enROUTE’; calculationmethod := ‘ANY’; ELSIF c4 IN (2131, 1800) THEN cardtype := ‘JBC’; calculationmethod := ‘MOD10′; END IF; ELSIF creditcardlength = 16 THEN IF c1 IN (4) THEN cardtype := ‘VISA’; calculationmethod := ‘MOD10′; ELSIF c1 IN (3) THEN
cardtype := ‘JBC’; calculationmethod := ‘MOD10′; ELSIF c2 IN (51, 52, 53, 54, 55) THEN cardtype := ‘MASTERCARD’; calculationmethod := ‘MOD10′; ELSIF c4 IN (6011) THEN cardtype := ‘DISCOVER’; calculationmethod := ‘MOD10′; END IF; END IF;
IF calculationmethod = ‘MOD10′ THEN FOR i IN REVERSE 1 .. LENGTH (creditcardnumber) LOOP IF cardtype = ‘AMEX’ THEN IF (TO_NUMBER (SUBSTR (TO_CHAR (i), LENGTH (i), 1)) NOT IN (1, 3, 5, 7, 9)) THEN t_value := SUBSTR (creditcardnumber, i, 1) * 2; subtotal := subtotal + SUBSTR (t_value, 1, 1); subtotal := subtotal + NVL (SUBSTR (t_value, 2, 1), 0); ELSE subtotal := subtotal + SUBSTR (creditcardnumber, i, 1); END IF; ELSE IF (TO_NUMBER (SUBSTR (TO_CHAR (i), LENGTH (i), 1)) IN (1, 3, 5, 7, 9)) THEN t_value := SUBSTR (creditcardnumber, i, 1) * 2; subtotal := subtotal + SUBSTR (t_value, 1, 1); subtotal := subtotal + NVL (SUBSTR (t_value, 2, 1), 0); ELSE subtotal := subtotal + SUBSTR (creditcardnumber, i, 1); END IF; END IF; END LOOP;
IF MOD (subtotal, 10) = 0 THEN RESULT := ‘VALID’; ELSE RESULT := ‘INVALID’; END IF; ELSIF calculationmethod = ‘ANY’ THEN RESULT := ‘VALID’; ELSE RESULT := ‘UNKNOWN’; END IF;
RESULT := RESULT ” ‘ ‘ ” cardtype; RETURN (RESULT);END;/
Simple PL/SQL script to remove the unwanted non-ascii characters from oracle or 11i database. This is an oracle function to remove extended ASCII code
Some of the fields are copied and pasted into oracle applications that comes with non-ascii characters.In such situation, the concurrent program fails and tracing the failure is really challenging issue.These characters are not visible while review. In some cases, data migration from sql server produces \0 (null) characters.
Here is plsql script that removes unwanted non-ascii characters from the data fields. Tested and working in 11i applications and oracle 10g database.
Download remove_nonascii
CREATE OR REPLACE FUNCTION REMOVE_NONASCII(P_TXT IN VARCHAR2)RETURN VARCHAR2 IS v_TMP VARCHAR2(32767); v_CLEAN VARCHAR2(32767); v_CHAR VARCHAR2(3); v_ERR VARCHAR2(32767);BEGIN FND_FILE.PUT_LINE(fnd_file.output,‘Entered String :: ‘ ” P_TXT); FOR i IN 1 .. LENGTH(P_TXT) LOOP v_CHAR := SUBSTR (P_TXT, i, 1);
IF (ASCII (v_CHAR) BETWEEN 32 AND 127) OR (ASCII (v_CHAR) IN (9, 10, 13)) THEN v_CLEAN := v_CLEAN ” v_CHAR; ELSE v_ERR := v_ERR ” v_CHAR; END IF; END LOOP;
IF LENGTH (v_CLEAN) != LENGTH (p_TXT) THEN FND_FILE.PUT_LINE(fnd_file.output,‘Removed ‘” TO_CHAR(LENGTH(P_TXT) – LENGTH(v_CLEAN)) ” ‘ Characters’); END IF;
FND_FILE.PUT_LINE(fnd_file.output,‘Modified String :: ‘ ” P_TXT);
RETURN v_CLEAN;END REMOVE_NONASCII;/
Courtesy, Copyright & thanks to my friend ashish
Find all the receipt methods associated with a receipt class
Here is the Script to Find all the receipt methods associated with a receipt class and organization id.
This is working code, verified in oracle 11i financial applications
/*****************Author: Substitute &ReceiptClassName and &org_id******************/
SELECT arm.name receipt_class, arc.name receipt_method, aba.bank_account_numFROM AR_RECEIPT_METHODS ARM, AR_RECEIPT_CLASSES ARC, AR_RECEIPT_METHOD_ACCOUNTS_ALL ARMA, AP_BANK_ACCOUNTS_ALL ABAWHERE 1=1AND arma.org_id=&org_idAND arm.name LIKE ‘&ReceiptClassName’AND arc.receipt_class_id=arm.receipt_class_idAND arm.receipt_method_id = arma.receipt_method_idAND arma.bank_account_id=aba.bank_account_id;
What are the profile setup values for ipayment gateway (oracle applications)?
There are few profile options to be set for ipayment gateway operations.The following script will find the values setup in the database (11i applications) for ipayment gateway
This is working code, verified in oracle 11i financial applications
/*****************Author:
******************/
SELECT t.user_profile_option_name "Profile Option", decode(a.level_id,10001,‘Site’,10002,‘Application’,10003,‘Responsibility’,10004,‘User’) "Level", decode(a.level_id,10001,‘Site’,10002,b.application_short_name,10003,c.responsibility_key,10004,d.user_name) "Level Value", a.profile_option_valueFROM fnd_profile_option_values a, fnd_application b, fnd_responsibility c, fnd_user d, fnd_profile_options e, fnd_profile_options_tl tWHERE a.profile_option_id = e.profile_option_id
AND e.profile_option_name IN (‘ICX_PAY_SERVER’,‘IBY_ECAPP_URL’,‘IBY_WALLET_LOCATION’,‘IBY_WALLET_PASSWD’,‘FND_DB_WALLET_DIR’) AND a.level_value = b.application_id(+) AND a.level_value = c.responsibility_id(+) AND a.level_value = d.user_id(+) AND t.profile_option_name = e.profile_option_name AND t.LANGUAGE = ‘US’ORDER BY a.level_id DESC;
How to find the receipt stuck in between stages?
Many times, the receipts are stuck in between stages.If these are noticed, all the receipts are stuck, and invoices many not be closed.Here is the sql to find the receipt stuck in between stages.This is working code, verified in oracle 11i financial applications
/*****************Author:
******************/
SELECT ab.org_id, ab.name, ab.batch_applied_status , ab.batch_date, count(*) FROM AR_PAYMENT_SCHEDULES_ALL aps, ar_batches_all abWHERE 1=1 —- uncomment this optional clause for faster response —- and to_char(ab.batch_date,’DD-MON-YYYY’) >= ‘01-JAN-2008′ AND ab.batch_applied_status NOT IN ( ‘COMPLETED_APPROVAL’,‘PROCESSED’,‘COMPLETED_FORMAT’)AND ab.type=‘CREATION’AND aps.selected_for_receipt_batch_id = ab.batch_idGROUP BY ab.org_id,ab.name,ab.batch_applied_status,ab.batch_date;
List all the concurrent Jobs ran by user. Here is the simple sql that gives you the all the concurrent Jobs ran by user.This is working code, verified in oracle 11i financial applications
/*****************Author: Substitute &user or pass as parameter******************/SELECT fcr.REQUEST_ID, FU.USER_NAME, fcr.PHASE_CODE, fcr.STATUS_CODE, (fcr.ACTUAL_COMPLETION_DATE – fcr.ACTUAL_START_DATE) * 24 * 60 TIME_MINS,
fcpt.USER_CONCURRENT_PROGRAM_NAME, fcp.CONCURRENT_PROGRAM_NAME, fcr.ACTUAL_START_DATE, fcr.ACTUAL_COMPLETION_DATE, fcp.CONCURRENT_PROGRAM_NAMEFROM apps.FND_CONCURRENT_REQUESTS FCR, apps.FND_CONCURRENT_PROGRAMS FCP, apps.FND_CONCURRENT_PROGRAMS_TL FCPT, apps.FND_USER FUWHERE 1=1AND FCP.CONCURRENT_PROGRAM_ID=FCR.CONCURRENT_PROGRAM_IDAND FCPT.CONCURRENT_PROGRAM_ID=FCP.CONCURRENT_PROGRAM_IDAND FCR.REQUESTED_BY = FU.USER_IDAND FU.USER_NAME = ‘&user’ORDER BY FCR.REQUEST_ID DESC;
How to find the log file and output file of a concurrent Job id? Here is the simple sql that gives you the log file and output file of a concurrent Job
/*****************Author: Substitute &1 or pass as parameter******************/SELECT fcr.request_id,fcr.outfile_name,fcr.logfile_name,fcr.argument_textFROM fnd_concurrent_requests fcrWHERE fcr.request_id IN ( &1);
Sample
SELECT fcr.request_id,fcr.outfile_name,fcr.logfile_name,fcr.argument_textFROM fnd_concurrent_requests fcrWHERE fcr.request_id IN ( 5594998 );
Handy tkprof sql creating script using bash shell unix, linux with oracle environment Oracle gives you this program called TKProf that reads your trace file and spits out somewhat meaningful output. My favorite option to tkprof is sort=prsela,fchela,exeela. This sorts the statements from longest running to shortest running. I prefer this format because I can concentrate on the top two or three statements for the most impact.
By tracing, I mean capturing all the SQL in a user’s session, or a SQL trace. As you can tell from the Oracle Performance Tuning Guide and Reference, there are many ways to enable tracing. Below are two methods I use as a DBA in my day-to-day routine.
Here is the script I often used to find the sql script using oracle trace utility for oracle applications forms, reports. Change the user id, password and database name to suit your environment.
Download TKprof shell script
#!/bin/sh#***********************************************# Script Name: tkp## Developed by #***********************************************# This script get the trace file name as argument and creates a tkprof file required for oracle analysis## Usage : tkp "oracle_trace_file"## Assumption: The oracle home environment set properly # The trace file suffix is .trc and is not provided as parameter argument# tkprof utility – unix – installed and oracle_home and path environment variables set# user id = apps, and password = apps#***********************************************if [ $@ > 0 ]thentkprof $1.trc $1.tkprof sort=exeela,fchela,prsela explain=apps/apps@PRODUCTIONelseecho ‘Usage : tkp "oracle_trace_file"’fi
Sometimes, a session is already underway and you need to start a trace midway through it’s execution. Here, you need to be a DBA and enable the 10046 event in the user’s session. This is a little more tricky since you have to know the sid and serial# from v$session in order to enable the tracing. For example,
SQL> SELECT sid, serial#, username2 FROM v$session3 WHERE username = ‘JEFFH’;
SID SERIAL# USERNAME———- ———- —————————— 25 5 JEFFH
SQL> exec sys.dbms_system.set_ev(25, 5, 10046,8,”);
PL/SQL procedure successfully completed.
Statements get written to the trace file when they are first encountered after the trace is started. The statement that is executing may not be in the final trace file.
Trace with TKProfPARAMETERSYou need 2 database parameters to trace sessions: TIMED_STATISTICS and USER_DUMP_DEST.
TIMED_STATISTICS should be TRUE to use statistics.Also possible so set this in a session:SQL> ALTER SESSION SET TIMED_STATISTICS=TRUE;
USER_DUMP_DEST points to the directory on the server where the tracefiles are being written.
Enable traceYou can enable tracing in the following ways:SQL*Plus:SQL> alter session set sql_trace true;
PL/SQL:dbms_session.set_sql_trace(TRUE);
DBASQL> execute sys.dbms_system.set_sql_trace_in_session(sid,serial#,TRUE);with: sid en serial# from the query:Select username, sid, serial#, machine from v$session;
Oracle forms:start forms with f45run32.exe statistics=yesor make a PRE-FORM trigger with the statement:forms_ddl(’alter session set sql_trace true’);
Oracle reports:BEFORE-REPORT trigger with statement:srw.do_sql(’alter session set sql_trace true’);
PRO*CEXEC SQL ALTER SESSION SET SQL_TRACE TRUE;
Use TKPROFTo make a tracefile readable, you need TKProf. Use the following command on the server:TKPROF tracefile exportfile [explain=username/password] [table= …] [print= ] [insert= ] [sys= ] [record=..] [sort= ]
The statements between brackets are optional. Their meaning is:explain=username/password: show an executionplan.table= schema.tabelnaam : use this table for explain planprint=integer restrict the number of shown SQL-statements.insert=bestandsnaam Show SQL-statements and data within SQL statements
sys = NO Don’t show statements that are executed under the SYS-schema. Most of the times these are recursive SQL-statements that are less interesting.Aggregate=NO Don’t aggregate SQL-statments that are executed more than once.sort= Sort the SQL-statements. The option is made up of 2 parts:part1:Prs Sorteer op parse-valuesExe Sorteer op executie-valuesfch Sorteer op fetch-values
Part 2:Cnt Sort on number of callsCpu Sort on CPU-usageEla Sort on elapsed timeDsk Sort on disk-readsQry Sort on consistent readsCu Sort on current readsMis Sort on library cache missesrow Sort on number of processed rows
I think Oracle uses tkprof as an acronym for Tom Kyte, Professor!
LUHN Algorithm Logic Algorithm for the Luhn Formula
LUHN Algorithm in C# (Validate Credit Card)
Credit Card validation LUHN algorithm using C
LUHN Algorithm – Validate credit card – in PHP
Validate the credit card (plsql code)!
Here’s how the algorithm for the Luhn formula works. Starting with a given credit card number,
1 2 3 4 – 5 6 7 8 – 9 0 1 2 – 3 4 5 2
we reverse the number, removing any non-numeric characters, to create a new string of digits like this (note that the checksum is now the first digit):
2 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1
Now we’ll look at each individual digit. Starting with the second digit in the string, we double every other number. The others are left alone.
2 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1
This creates a new string of digits shown here:
2 10 4 6 2 2 0 18 8 14 6 10 4 6 2 2
Finally, we go through this new string and add up each single digit to produce a total. In other words, for this example, we don’t add 2 + 10 + … but 2 + 1 + 0 + … instead:
2 + 1 + 0 + 4 + 6 + 2 + 2 + 0 + 1 + 8 + 8 + 1 + 4 + 6 + 1 + 0 + 4 + 6 + 2 + 2 = 60
Use your browser’s
View Source
option to see the full source code.
If this sum is an integer multiple of 10 (e.g., 10, 20, 30, 40, 50,…) then the card number is valid, as far as the checksum is concerned.
Here is the JavaScript code to sum the digits, where
r
represents the card number as a string of digits already in reverse order.
// Run through each single digit to create a new string. Even digits // are multiplied by two, odd digits are left alone.
t = ""; for (i = 0; i < r.length; i++) { c = parseInt(r.charAt(i), 10); if (i % 2 != 0) c *= 2; t = t + c; }
// Finally, add up all the single digits in this string.
n = 0; for (i = 0; i < t.length; i++) { c = parseInt(t.charAt(i), 10); n = n + c; }
Once the sum is found, the code checks to see if it’s an even multiple of ten (i.e., n % 10 leaves no remainder).
// If the resulting sum is an even multiple of ten (but not zero), the // card number is good.
if (n != 0 && n % 10 == 0)
return true; else return false;}
Programming Note
You may have noticed that the checksum digit (2) is included in the sum. Rather than adding up the other digits and calculating the valid checksum value for comparison, it’s included in the total to save some programming steps.
In other words, if you were creating a new card number and wanted to find the right checksum digit, you’d total up the other digits as shown above except that you wouldn’t have the initial digit (2).
1 + 0 + 4 + 6 + 2 + 2 + 0 + 1 + 8 + 8 + 1 + 4 + 6 + 1 + 0 + 4 + 6 + 2 + 2 = 58
Using the total (58) you’d take the next highest number that is evenly divisible by ten and subtract the total from this to produce the proper checksum digit (60 – 58 = 2 in this case).
If the total was already an even multiple of ten, say 70, the checksum would simply be zero.
To save a couple of steps in the code, the checksum digit is included in the calculation so that the sum should be an integer multiple of ten.
How To Extract,Using Bash/Unix/Linux Shell Scripting, The Oracle Data Like Excel Report And Send As Email Attachment?
This script provides an sample, and then the practical example to connect to oracle database, extract data like excel sheet and attach it with an email list.
First connecting is done with “sqlplus -s $FCP_LOGIN” in silent mode.Then EOF marks the begining of sql statement and another EOF marks end of it.The chr(9) provides the tab required to make this as excel sheet.In fact, it creates a csv file with tab delimited entry.Since the filename ‘FILENAME=”Credit_Card_Failure_Report.xls”‘ ends with xls sheet, when the user opens the file, it automatically converts into excel sheet.The UUENCODE attaches the file as email attachment.
Practical Example1
Practical Example2
#!/bin/sh#
# P_EMAIL_ADDRESS_TO is a parameter from the concurrent job#P_EMAIL_ADDRESS_TO="@notesbit.com"## FCP_LOGIN is standard in oracle applications, here I substituted
FCP_LOGIN="apps/pwd@database"
FILENAME="user_report.xls"sqlplus -s $FCP_LOGIN<<EOFSET echo OFFSET feedback OFF SET heading offSET linesize 221 SET pagesize 0 SET newpage 0spool $FILENAME
SELECT RPAD (SUBSTR (username, 1, 15), 15, ‘ ‘) ”chr(9) ” RPAD (SUBSTR (emails, 1, 15), 15, ‘ ‘) ”chr(9) FROM all_users;
EOF
if [ -f $FILENAME ]then uuencode $FILENAME $FILENAME ‘ mail -s "$FILENAME status! Reported on `date` " "$P_EMAIL_ADDRESS_TO"fi
Oracle applications (11i) Invalid credit cards in bank records report
Oracle applications (11i) daily credit card failure report – ipayment gateway
Bash script – Passing arguments to the shell script Unix/Linux. Oracle Applications:Checking Credit Card Number validity in Internet
Expenses, iPayments using Luhn algorithm (modulus 10) Paymentech file comparison in Linux
How To Extract,Using Bash/Unix/Linux Shell Scripting, The Oracle Data Like Excel Report And Send As Email Attachment?
Credit cards are loaded through interfaces. Oracle application, by default, accepts any value as this varchar2 format. However, the credit cards should be listed as a continuous number without any space or dashes or any special chars.
We can try to eliminate these at source using filter in loader control file. Still some of them elusive like termination char “\0″. This is common when the source of the data comes from mysql server or sybase.These are invisible naked eye. You can review this with dump command. This program identifies all the invisible or unwanted or special chars.
If there is any hit, then only it will send an email. Otherwise no emails sent. This is handled at “if [ $FILESIZE -gt 444 ]“. Without a hit it produces 444 bytes file.
Download invalid_credit_cards_at_bank_records.sh
#!/bin/sh/** Author: @notesbit.com*/old_args=$@#FILENAME="Invalid_credit_cards_in_bank_records.xls"P_EMAIL_ADDRESS_TO=`echo $old_args ‘cut -f9 -d’ ‘ ‘ cut -f2 -d‘=’ ‘ sed ‘s/"//g’`##source /usr/local/bin/PRODUCTION.env # For test purposes#if [ -f $FILENAME ]then rm -rf $FILENAME echo "Old Data File ($FILENAME) deleted…"fi##echo $FILENAME#echo "$P_EMAIL_ADDRESS_TO"#sqlplus -s $FCP_LOGIN<<EOFSET echo OFFSET feedback OFF SET heading offSET linesize 221 SET pagesize 0 SET newpage 0
–alter session set current_schema=apps; — For test purposes
spool $FILENAME
select ‘Invalid_credit_cards_in_bank_records:To be corrected at source’ from dual;
select ‘customer_name’ ” chr(9) ” ’Invoice_number’ ” chr(9) ” ’Dump CC Number”’ chr(9) ” ’Credit Card Name’ ” chr(9) ” ’Credit Card Number”’ chr(9) ” ’ Credit Card Validity’ ” chr(9) ” ’Invoice Amount’ from dual;
select rc.customer_name ” chr(9) ” rct.trx_number ” chr(9) ”
to_char(dump(apa.bank_account_num))” chr(9) ” apa.bank_account_name ” chr(9) ” ’************”’substr(apa.bank_account_num,-4) ” chr(9) ” apa.inactive_date ” chr(9) ” aps.AMOUNT_DUE_REMAINING from ap_bank_accounts_all apa, ra_customer_trx_all rct, ra_customers rc, ar_payment_schedules_all aps, RA_BATCH_SOURCES_ALL RBSwhere 1=1 AND RBS.NAME =’InvoiceSourceName’ — change to actual valueAND RCT.BATCH_SOURCE_ID = RBS.BATCH_SOURCE_IDand rct.customer_trx_id = aps.customer_trx_idand aps.status = ‘OP’and apa.bank_account_id = rct.customer_bank_account_idand rc.customer_id = rct.bill_to_customer_idand replace(replace(replace(replace(apa.bank_account_num,chr(0),null),chr(32),null),chr(45),null),chr(95),null)<>apa.bank_account_numAND aPS.gl_date_closed = TO_DATE(’4712/12/31′, ‘YYYY/MM/DD’)AND aps.selected_for_receipt_batch_id IS NULLand rct.creation_date >= to_date (’01-FEB-2005′,’DD-MON-YYYY’) — For better performance, this can be removed and rct.attribute9=’CREDIT CARD’AND aps.reserved_type IS NULLAND aps.reserved_value IS NULLand length(replace(replace(replace(replace(apa.bank_account_num,chr(0),null),chr(32),null),chr(45),null),chr(95),null)) in ( 15, 16 );
EOF
if [ -f $FILENAME ]then FILESIZE=$(stat -c%s "$FILENAME") if [ $FILESIZE -gt 444 ] then uuencode $FILENAME $FILENAME ‘ mail -s "$FILENAME. Reported on `date` " "$P_EMAIL_ADDRESS_TO"# uuencode $FILENAME $FILENAME ‘ mail -s "$FILENAME. Reported on `date` " "@notesbit.com" fifi
Oracle applications (11i) daily credit card failure report – ipayment gateway
Oracle Applications:Checking Credit Card Number validity in Internet Expenses, iPayments using Luhn algorithm (modulus 10)
Auto shipment notification to companies using oracle applications – Concurrent Job shell script
Get Credit Card Number for an invoice (oracle 11i) Get Credit Card Number for a customer number (oracle 11i)
Oracle applications (11i) Invalid credit cards in bank records report
User needs the daily credit card failure report to follow-up with customers. This will attach the generated excel sheet and send the email to the list of users. This is registered as unix host concurrent Program in oracle applications. This can also be simply modified as a crontab report. This is a practical example of unix / linux with oracle applications producing excel sheet. The attachment is possible as UUENCODE.
Download oracle_ipayment_credit_card_failure_report.sh
#!/bin/sh## Author: # # P_EMAIL_ADDRESS_TO is a parameter from the concurrent job#old_args=$@
FILENAME="Credit_Card_Failure_Report.xls"P_EMAIL_ADDRESS_TO=`echo $old_args ‘cut -f9 -d’ ‘ ‘ cut -f2 -d‘=’ ‘ sed ‘s/"//g’`#source /usr/local/bin/PRODUCTION.env # For test purposesif [ -f $FILENAME ]then rm -rf $FILENAME echo "Old Data File ($FILENAME) deleted…"fiecho $FILENAMEecho "$P_EMAIL_ADDRESS_TO"sqlplus -s $FCP_LOGIN<<EOFSET echo OFFSET feedback OFF SET heading offSET linesize 221 SET pagesize 0 SET newpage 0spool $FILENAME
SELECT RPAD (SUBSTR (a, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (b, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (c, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (d, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (e, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (f, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (g, 1, 16), 16, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (h, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (i, 1, 15), 15, ‘ ‘)
” chr(9) ” RPAD (SUBSTR (j, 1, 15), 15, ‘ ‘) ” chr(9) ” RPAD (SUBSTR (to_char(k), 1, 15), 15, ‘ ‘)”chr(9) FROM ( select a,b,c,d,e,f,g,h,max(i) i,j,k from ( SELECT decode(rct.org_id,262,’China Operating Unit’,283,’Europe Operating Unit’,303,’India Operating Unit’,307,’UK Operating Unit’,311,’Australia Operating Unit’,315,’Japan Operating Unit’,319,’Hong Kong Operating Unit’,223,’US Operating Unit’) a ,ac.customer_number b ,ac.customer_name c ,rct.attribute2 d ,rct.trx_date e ,rct.trx_number f ,rt.NAME g ,LPAD (SUBSTR (aba.bank_account_num,LENGTH (aba.bank_account_num)-3,4), LENGTH (aba.bank_account_num),’*’ ) h ,nvl(max(its.bepmessage),’Declined’) i ,acol.NAME j ,aps.amount_due_remaining k FROM RA_CUSTOMER_TRX_ALL RCT ,RA_TERMS RT ,AP_BANK_ACCOUNTS_ALL ABA ,AR_CUSTOMERS AC ,AR_CUSTOMER_PROFILES ACP ,AR_COLLECTORS ACOL ,AR_PAYMENT_SCHEDULES_ALL APS ,RA_BATCH_SOURCES_ALL RBS ,APPS.IBY_TRXN_SUMMARIES_ALL ITS WHERE 1=1 AND RCT.CUSTOMER_BANK_ACCOUNT_ID = ABA.BANK_ACCOUNT_ID AND RCT.BILL_TO_CUSTOMER_ID = AC.CUSTOMER_ID AND RCT.BATCH_SOURCE_ID = RBS.BATCH_SOURCE_ID AND ACP.CUSTOMER_ID = AC.CUSTOMER_ID AND ACP.COLLECTOR_ID = ACOL.COLLECTOR_ID AND RCT.TERM_ID = RT.TERM_ID AND APS.CUSTOMER_TRX_ID = RCT.CUSTOMER_TRX_ID AND ACP.SITE_USE_ID IS NULL AND APS.AMOUNT_DUE_REMAINING > 0 AND APS.ORG_ID > 202 AND ITS.INSTRNUMBER = APPS.IBY_INSTRREG_PUB.ENCODE (ABA.BANK_ACCOUNT_NUM) AND ITS.STATUS <> 0 AND ITS.CREATION_DATE >= SYSDATE – 2*365 AND ITS.STATUS > 0 AND ITS.INSTRTYPE = ‘CREDITCARD’ AND RCT.CREATION_DATE >= SYSDATE – 2*365 AND RCT.ORG_ID > 202 AND ABA.ACCOUNT_TYPE=’EXTERNAL’ AND RCT.ORG_ID = APS.ORG_ID GROUP BY decode(rct.org_id,262,’China Operating Unit’,283,’Europe Operating Unit’,303,’India Operating Unit’,307,’UK Operating Unit’,311,’Australia Operating Unit’,315,’Japan Operating Unit’,319,’Hong Kong Operating Unit’,223,’US Operating Unit’) ,ac.customer_number ,ac.customer_name ,rct.attribute2 ,rct.trx_date
,rct.trx_number ,rt.NAME ,LPAD (SUBSTR (aba.bank_account_num,LENGTH (aba.bank_account_num)-3,4), LENGTH (aba.bank_account_num),’*’ ) ,acol.NAME ,aps.amount_due_remaining unionSELECT decode(rct.org_id,262,’China Operating Unit’,283,’Europe Operating Unit’,303,’India Operating Unit’,307,’UK Operating Unit’,311,’Australia Operating Unit’,315,’Japan Operating Unit’,319,’Hong Kong Operating Unit’,223,’US Operating Unit’) a ,ac.customer_number b ,ac.customer_name c ,rct.attribute2 d ,rct.trx_date e ,rct.trx_number f ,rt.NAME g ,LPAD (SUBSTR (aba.bank_account_num,LENGTH (aba.bank_account_num)-3,4), LENGTH (aba.bank_account_num),’*’ ) h ,nvl(max(its.bepmessage),’Invalid CC or expiry date’) i ,acol.NAME j ,aps.amount_due_remaining k FROM RA_CUSTOMER_TRX_ALL RCT ,RA_TERMS RT ,AP_BANK_ACCOUNTS_ALL ABA ,AR_CUSTOMERS AC ,AR_CUSTOMER_PROFILES ACP ,AR_COLLECTORS ACOL ,AR_PAYMENT_SCHEDULES_ALL APS ,RA_BATCH_SOURCES_ALL RBS ,APPS.IBY_TRXN_SUMMARIES_ALL ITS WHERE 1=1 AND RCT.CUSTOMER_BANK_ACCOUNT_ID = ABA.BANK_ACCOUNT_ID AND RCT.BILL_TO_CUSTOMER_ID = AC.CUSTOMER_ID AND RCT.BATCH_SOURCE_ID = RBS.BATCH_SOURCE_ID AND ITS.INSTRNUMBER(+) = APPS.IBY_INSTRREG_PUB.ENCODE (ABA.BANK_ACCOUNT_NUM) AND nvl(ITS.STATUS,1) <> 0 –AND ITS.CREATION_DATE >= SYSDATE – 2*365 –AND ITS.STATUS > 0 — AND ITS.INSTRTYPE = ‘CREDITCARD’ AND ACP.CUSTOMER_ID = AC.CUSTOMER_ID AND ACP.COLLECTOR_ID = ACOL.COLLECTOR_ID AND RCT.TERM_ID = RT.TERM_ID AND APS.CUSTOMER_TRX_ID = RCT.CUSTOMER_TRX_ID AND ACP.SITE_USE_ID IS NULL AND APS.AMOUNT_DUE_REMAINING > 0 AND APS.ORG_ID > 202 AND RCT.CREATION_DATE >= SYSDATE – 2*365 AND RCT.ORG_ID > 202 AND ABA.ACCOUNT_TYPE=’EXTERNAL’ AND RCT.ORG_ID = APS.ORG_ID AND ( RCT.CC_ERROR_FLAG IS NOT NULL ) AND RCT.CC_ERROR_CODE IS NULL
GROUP BY decode(rct.org_id,262,’China Operating Unit’,283,’Europe Operating Unit’,303,’India Operating Unit’,307,’UK Operating Unit’,311,’Australia Operating Unit’,315,’Japan Operating Unit’,319,’Hong Kong Operating Unit’,223,’US Operating Unit’) ,ac.customer_number ,ac.customer_name ,rct.attribute2 ,rct.trx_date ,rct.trx_number ,rt.NAME ,LPAD (SUBSTR (aba.bank_account_num,LENGTH (aba.bank_account_num)-3,4), LENGTH (aba.bank_account_num),’*’ ) ,acol.NAME ,aps.amount_due_remaining)GROUP BY a,b,c,d,e,f,g,h,j,k);
EOF
if [ -f $FILENAME ]then uuencode $FILENAME $FILENAME ‘ mail -s "$FILENAME status! Reported on `date` " "$P_EMAIL_ADDRESS_TO"# uuencode $FILENAME $FILENAME ‘ mail -s "$FILENAME status! Reported on `date` " "@notesbit.com" # For test purposes only!fi
Oracle Application Performance Tuning Scripts
One of the biggest responsibilities of a DBA is to ensure that the Oracle database is tuned properly. The Oracle RDBMS is highly tunable and allows the database to be monitored and adjusted to increase its performance.
One should do performance tuning for the following reasons:
* The speed of computing might be wasting valuable human time (users waiting for response);* Enable your system to keep-up with the speed business is conducted; and* Optimize hardware usage to save money (companies are spending millions on hardware).
Here are the oracle performance tuning scripts used in oracle applications.I will be adding more information about this scripts soon
Remember: They are used in oracle applications 11i version.
active.sqlafimmethod.sqlalter_tbs.sqlanalyzepending.sqlanalyzereq.sql
appproc.sqlapps_alerts.sqlappsi1.sqlappsid.sqlappuser.sqlappusers.sqlaps_lock.sqlarchlogs.sqlbadge.sqlbbwfiles.sqlbbwsid.sqlbcfootprint.sqlbde_chk_cbo.sqlbigtemptabs.sqlbigtsobj.sqlccmospid.sqlckactmt.sqlckfsstat.sqlckhwm.sqlckiostat.sqlckkept.sqlcklibcache.sqlckmodules.sqlckmt.sqlcknotkeptdet.sqlckobj.sqlckobjstats.sqlckownerstats.sqlckrbs.sqlcktempts.sqlcktsdf.sqlckufs.sqlckurbs.sqlcmadmin.sqlcmclean.sqlcmdailylongj.sqlcmdailylong.sqlcmlong.sqlcmpending.sqlcmpend.sqlcmqhourly.sqlcmqjobs.sqlcmqrdet.sqlcmqrtimes.sqlcmquickq.sqlcmqwdet.sqlcmqwtimes.sqlcmreq.sqlcmrun.sqlcmtoday.sqlcoe_stats.sqlcount_md_recs.sql
dbms_lock_allocated.sqldbsize.sqlexplain_s2.sqlexplain_s.sqlfbwsid.sqlfix_invflag.sqlformid.sqlformuser.sqlfrag2.sqlfragmentation.sqlfree_space.sqlfts.sqlgetplsqldef.sqlhashopensql.sqlhashsql.sqlhashstats.sqlhotbkupstat.sqlhotblocks.sqlhotobjects.sqlinactive.sqlindex.sqlinitora.sqlinv_obj.sqliowaitsdf.sqljobhistdet.sqljobhist.sqljobid.sqlkgl_mod3.sqlkgl.sqlkillcmreq.sqllast10jobs.sqllast10userjobs.sqllast_run_date.sqllclholder.sqllholder.sqllocksumm.sqllock_wait1.sqllock_waits.sqllogstatus.sqllongops.sqllong_run.sqllsleep.sqllwait.sqlmaxdfrdtm.sqlmaxwaits.sqlmodopensql.sqlmtptdf.sqlmtpt.sqlnewblockers.sqlnewses.sqlnewwaiters.sqlnotextend.sql
object.sqlobjlocks.sqlobjs_in_cache.sqlosproc.sqlparttabinfo.sqlperftest_forms2.sqlperftest_forms.sqlperftest_logins.sqlpo_reapprove.sqlpxbuffers.sqlpxiostats.sqlpxprocs.sqlpxsession.sqlpxslave.sqlpxsorts.sqlpxstats.sqlqcsid.sqlrealname.sqlrecentses.sqlrecompile_sql.sqlredo.sqlredostats.sqlretry_all_invoice.sqlretry_wf_500.sqlretry_wf.sqlrolesgrants.sqlsegactivity.sqlsesswork.sqlsidevents.sqlsidlock.sqlsidlongops.sqlsidopensql.sqlsidsort.sqlsid.sqlsidsql.sqlsidtime.sqlsidwait.sqlsidwaits.sqlsorttypes.sqlsparse_indexes.sqlsparse_tables.sqlspexecs.sqltemp_alert.sqltemp_conc_prog.sqltest1.sqltop10active.sqltop10active.sql.baktop10cpu.sqltop10extents.sqltop10hogs.sqltop10inactive.sqltop10jobs.sql
top10opencurs.sqltop10seswaits.sqltop10sorts.sqltop10spid.sqltop10sysevents.sqltopreaddf.sqltopwritedf.sqltsbufhit.sqltsdcmrat.sqltslcmrat.sqltstsid.sqltst.sqltsusage.sqlwaits_alerts.sqlwaits.sqlwebmethods_work.sqlwhereami.sqlwhosort.sql
Tuning & Performance – Gather Statistics importance
Oracle performance tuning – Gather Statistics:
Here is the one issue: I have same script using two tables as given below, running in two databases. The data, table names, indexes and the select statements are same. One database the query is running fast and another query is slow.
SELECT MAS.site_use_id, MAS.currency, DET.customer_id FROM table_master MAS, table_detail DET WHERE MAS.attribute1 = :Value AND DET.pk_id = MAS.pk_id AND MAS.site_use_id = DET.site_use_idORDER BY MAS.site_use_id, MAS.currency;
In one database the scan is full table scan and in other uses index perfectly.
Plan
SELECT STATEMENT CHOOSE Cost: 49 Bytes: 114 Cardinality: 16 SORT ORDER BY Cost: 49 Bytes: 114 Cardinality: 15 NESTED LOOPS Cost: 2 Bytes: 114 Cardinality: 12 TABLE ACCESS BY INDEX ROWID APPS.table_master Cost: 1 Bytes: 95 Cardinality: 11 INDEX RANGE SCAN NON-UNIQUE APPS.XXCFI_MAS_ATTR1_N2 Cost: 1 Cardinality: 14 TABLE ACCESS BY INDEX ROWID CCA.table_detail Cost: 1 Bytes: 19
Cardinality: 13 INDEX UNIQUE SCAN UNIQUE CCA.table_detail_U1 Cardinality: 1
Plan
SELECT STATEMENT CHOOSE Cost: 62 Bytes: 282 Cardinality: 66 SORT ORDER BY Cost: 62 Bytes: 282 Cardinality: 65 COUNT STOPKEY4 HASH JOIN Cost: 38 Bytes: 282 Cardinality: 62 TABLE ACCESS BY INDEX ROWID APPS.table_master Cost: 5 Bytes: 35,084 Cardinality: 1,2531 INDEX RANGE SCAN NON-UNIQUE APPS.XXCFI_MAS_ATTR1_N2 Cost: 4 Cardinality: 1,2533 TABLE ACCESS FULL CCA.table_detail Cost: 32 Bytes: 181,545 Cardinality: 9,555
Then, what is wrong? The possible reason may be due to gather_statistics & estimation.You need to use the following gather statistics periodically.
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_N1′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_N2′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_U1′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘table_detail_U2′, estimate_percent => 30);
exec DBMS_STATS.gather_index_stats(‘APPS’, ‘XXCUS_EXP_DTL_N1′, estimate_percent => 30);
Current Period Status of Application (oracle 11i) /*Description: This script current period status of application (oracle 11i)Author: Gopal / Input: &&Chart_of_accounts_id,&&application_id*/
SELECT gls.name, gps.closing_status FROMapps.GL_PERIOD_STATUSES gps, gl_sets_of_books glsWHERE 1=1AND gps.start_date <= SYSDATEAND gps.end_date >= SYSDATEAND gps.set_of_books_id = gls.set_of_books_idAND gps.application_id=&&application_idAND gls.chart_of_accounts_id=&&Chart_of_accounts_id
AND gls.name IN ( ‘OPER US’,‘OPER Australia’,‘OPER Japan’,‘OPER UK’, ‘OPER Hong Kong’,‘OPER Europe’,‘OPER China’ );
Pending normal jobs running (oracle 11i) in oracle applications
/*Description: This script will all the pending normal jobs running (oracle 11i) in oracle applicationsBackend query is always faster than front end queryAuthor: Gopal / Input: none*/
Download the Code
SELECTfcr.REQUEST_ID,fu.user_name,fcr.PHASE_CODE,fcr.STATUS_CODE,(fcr.ACTUAL_COMPLETION_DATE – fcr.ACTUAL_START_DATE) * 24 * 60 TIME_MINS,fcpt.USER_CONCURRENT_PROGRAM_NAME,fcp.CONCURRENT_PROGRAM_NAME,fcr.ACTUAL_START_DATE,fcr.ACTUAL_COMPLETION_DATE,fcp.CONCURRENT_PROGRAM_NAMEFROMapps.FND_CONCURRENT_REQUESTS FCR,apps.FND_CONCURRENT_PROGRAMS FCP,apps.FND_CONCURRENT_PROGRAMS_TL FCPT,apps.FND_USER FUWHERE 1=1AND fcr.PHASE_CODE = ‘P’ — PendingAND fcr.STATUS_CODE = ‘I’ — NormalAND fcp.CONCURRENT_PROGRAM_ID=fcr.CONCURRENT_PROGRAM_IDAND fcpt.CONCURRENT_PROGRAM_ID=fcp.CONCURRENT_PROGRAM_IDAND FCR.REQUESTED_BY = FU.USER_IDORDER BY fcr.request_id DESC;
Get Credit Card Number for a customer number (oracle 11i) –– Description: For any customer number, this gives credit card or bank account number (oracle 11i)– Author: Gopal / – Input: &&Cust_number–
Download the code
SELECTRC.CUSTOMER_NAME,RC.CUSTOMER_NUMBER,BACCT.BANK_ACCOUNT_NAME BANK_NAME,BACCT.BANK_ACCOUNT_NUM CREDIT_CARD_NUMBER,TO_CHAR(bacct.inactive_date,’DD-MON-YYYY’) CREDIT_VALIDAITY_DATE, BANK_ACCOUNT_USES_id, BACCT.BANK_ACCOUNT_IDFROMAP_BANK_ACCOUNT_USES_ALL BAUSES,AP_BANK_BRANCHES BBNCH,AP_BANK_ACCOUNTS_ALL BACCT,RA_CUSTOMERS RCWHERE 1=1AND BAUSES.EXTERNAL_BANK_ACCOUNT_ID = BACCT.BANK_ACCOUNT_IDAND BACCT.BANK_BRANCH_ID = BBNCH.BANK_BRANCH_IDAND BAUSES.CUSTOMER_ID = RC.CUSTOMER_IDAND RC.CUSTOMER_NUMBER IN ( ‘&&Cust_number‘);
Get Credit Card Number for an invoice (oracle 11i) /*Description: This script will find the credit card numberfor an invoice number (oracle 11i)Author: Gopa l/ Input: &&inv_no*/
selectrc.customer_name customer,rct.trx_number invoice_number,apa.bank_account_id,apa.bank_account_name bank_name,apa.bank_account_num credit_card_number,to_char(apa.inactive_date,’dd-mon-yyyy’) credit_validaity_date,rct.invoice_currency_code,rct.org_idfromap_bank_accounts_all apa,ra_customer_trx_all rct,ra_customers rcwhere 1=1and apa.bank_account_id = rct.customer_bank_account_idand rc.customer_id = rct.bill_to_customer_idand rct.trx_number in (’&&inv_no‘);
Auto shipment notification to companies using oracle applications – Concurrent Job shell script The customer needs an automatic notification, like an alert, whenever a shipment goes through. A trigger is put in place to insert a shipment record in a custom table for better performance. A concurrent job – unix shell script is designed to run every 15 minutes to pickup the details and dispatch an email attachment to the group email of the receiving company. This uses a utility called mpack to attach the data-output with the email group. You can also use uuencode instead. Here the complete script that show the elegance of Shell script.
As you know, there may be other ways to hand this script. This is one of the ways! Feel free to copy and use it.
Sample script with more details – ( How to extract,using bash/unix/linux shell scripting )
Download the code
#!/bin/sh# autoship.sh#===============================================================================# This routine takes the COMPANY shipments AND emails TO the GROUP email id# GROUP Email ID: [email protected]# Author: DATE:Apr 26, 2002# Modified ON May 6,2002 TO divide the files per invoice# Modified ON May 14,2002 GROUP Email [email protected]# Modified ON May 29,2002 TO remove conrtol chars FROM email utility# Modified ON Jun 06,2002 TO ADD attribute4 (Flex Field) checking IN the query#===============================================================================DATPATH=$XXCUS_TOP/import/dat; export DATPATHFILENAME=$DATPATH/company_INVOICES.datIF [ -f $FILENAME ]THENrm -f $FILENAMEecho "Old Data File deleted…"fi
sqlplus -s $1 <SET echo OFFSET feedback OFFSET linesize 240SET pagesize 0SET newpage 0COLUMN header_line format A210COLUMN lin format 9999 NOPRINTCOLUMN inv Format A20 NOPRINT
INSERT INTO company_invoicesSELECTih.trx_number,NULLFROM
ra_customers cs,ra_customers cs2,ra_customer_trx_all ih,ra_customer_trx_lines_all idWHEREid.customer_trx_id = ih.customer_trx_id ANDid.line_type = ‘LINE’ ANDih.ship_to_customer_id = cs.customer_id ANDih.bill_to_customer_id = cs2.customer_id ANDcs.customer_name = ‘COMPANY CORPORATION’ ANDih.creation_date >= TRUNC(sysdate-40) ANDih.creation_date < TRUNC(sysdate+1) ANDih.trx_number NOT LIKE ‘%CM%’ ANDih.attribute4 = ‘COMPANY’ ANDih.trx_number NOT IN ( SELECT NVL(invoice_no,0) FROM company_invoices WHERE date_sent IS NOT NULL )GROUP BY ih.trx_number;
spool $FILENAMESELECTih.trx_number inv,1 lin,‘I~H~’”ih.trx_number”‘~’”””‘~~’”TO_CHAR(ih.TRX_DATE,‘YYYYMMDD’)”‘~’”RTRIM(cs2.customer_name)”‘~’”ih.purchase_order”‘~’”LTRIM(TO_CHAR(SUM(id.extended_amount),‘9999999990.00′))”‘~’”DECODE(ih.ship_to_customer_id,ih.bill_to_customer_id,‘P’,‘L’) header_lineFROMra_customers cs,ra_customers cs2,ra_customer_trx_all ih,ra_customer_trx_lines_all idWHEREid.customer_trx_id = ih.customer_trx_id ANDid.line_type = ‘LINE’ ANDih.ship_to_customer_id = cs.customer_id ANDih.bill_to_customer_id = cs2.customer_id ANDcs.customer_name = ‘COMPANY CORPORATION’ ANDih.creation_date >= TRUNC(sysdate-40) ANDih.creation_date < TRUNC(sysdate+1) ANDih.trx_number NOT LIKE ‘%CM%’ ANDih.attribute4 = ‘COMPANY’ ANDih.trx_number IN ( SELECT NVL(invoice_no,0) FROM company_invoices WHERE date_sent IS NULL)GROUP BY ih.trx_number,ih.TRX_DATE,cs2.customer_name,ih.purchase_order,DECODE(ih.ship_to_customer_id,ih.bill_to_customer_id,‘P’,‘L’)UNIONSELECTih.trx_number inv,2 lin,‘I~S~’”ih.trx_number”‘~’”cs.customer_name”‘~’”ad.address1”‘~’”ad.address2”‘~’”ad.city”‘~’”ad.state”‘~’”ad.postal_code header_lineFROMra_customers cs,ra_customer_trx_all ih,ra_customer_trx_lines_all id,ra_site_uses_all st,ra_addresses_all adWHERENVL(ih.ship_to_site_use_id,ih.bill_to_site_use_id) = st.site_use_id ANDst.address_id = ad.address_id ANDid.customer_trx_id = ih.customer_trx_id ANDNVL(ih.ship_to_customer_id,ih.bill_to_customer_id) = cs.customer_id ANDid.line_type = ‘LINE’ ANDcs.customer_name = ‘COMPANY CORPORATION’ ANDih.creation_date >= TRUNC(sysdate-40) ANDih.creation_date < TRUNC(sysdate+1) AND
ih.trx_number NOT LIKE ‘%CM%’ ANDih.attribute4 = ‘COMPANY’ ANDih.trx_number IN ( SELECT NVL(invoice_no,0) FROM company_invoices WHERE date_sent IS NULL)GROUP BY ih.trx_number,cs.customer_name,ad.address1,ad.address2,ad.city,ad.state,ad.postal_codeUNIONSELECTih.trx_number inv,id.line_number+2 lin,‘I~D~’”ih.trx_number”‘~’”mm.name”‘~~’”RTRIM(REPLACE(REPLACE(id.description,CHR(10),”),CHR(13),”))”‘~’”DECODE(id.interface_line_attribute2,‘X’,NULL,NULL,NULL,RTRIM(mm.name)”id.interface_line_attribute2)”‘~~~’”DECODE(LOWER(id.interface_line_attribute2),‘x’,‘O’,‘H’)”‘~’”TO_CHAR(id.quantity_invoiced)”‘~’”LTRIM(TO_CHAR(id.extended_amount,‘9999999990.00′)) header_lineFROMra_customers cs,ra_customer_trx_all ih,ra_customer_trx_lines_all id,ar_memo_lines_all mmWHEREmm.memo_line_id = id.memo_line_id ANDid.customer_trx_id = ih.customer_trx_id ANDNVL(ih.ship_to_customer_id,ih.bill_to_customer_id) = cs.customer_id ANDid.line_type = ‘LINE’ ANDcs.customer_name = ‘COMPANY CORPORATION’ ANDih.creation_date >= TRUNC(sysdate-40) ANDih.creation_date < TRUNC(sysdate+1) ANDih.trx_number NOT LIKE ‘%CM%’ ANDih.attribute4 = ‘COMPANY’ ANDih.trx_number IN ( SELECT NVL(invoice_no,0) FROM company_invoices WHERE date_sent IS NULL)ORDER BY inv,lin;spool off
UPDATE company_invoices SET date_sent = SYSDATE WHERE date_sent IS NULL;
COMMIT;
EOFecho "End of select SQL …"IF [ -f $FILENAME ]THENecho "SQL successfully generated a file…"FILE_SIZE=`wc -c $FILENAME ‘ awk ‘{print $1}’`IF [ $FILE_SIZE = 0 ]; THENecho "File does not contain any data…"EXIT 0ELSEINVLIST=`cut -d~ -f3 $FILENAME ‘ sort -u`FOR INVNO IN $INVLISTDOgrep "^….$INVNO" $FILENAME ‘ sed ‘s/ //g‘ ‘ sed ’s/$’"/`echo \\\r`/g" > invoice.txtmpack -s "COMPANY Shipment Details for Invoice No:$INVNO from DATE:`date`" invoice.txt [email protected] -f invoice.txtdoneecho "Email sent to group…"EXIT 0fiELSE
echo "COMPANY failed at `date`" ‘ mailx -s "COMPANY SHIPMENT DETAILS FAILED at `date`" [email protected] "Email sent to admin about failure …"fi
Send e-mail messages and attachments from PL/SQL
I am not the author of this plsql. Just reproduced from the source site. The original copyright and credit goes to the Author.
Send e-mail messages and attachments from PL/SQL From Oracle8i release 8.1.6 one can send e-mail messages directly from PL/SQL using either the UTL_TCP or UTL_SMTP packages. Jserver needs to be installed and configured. No pipes or external procedures required.
rem ———————————————————————-rem Filename: smtp-att.sqlrem Purpose: Send e-mail messages and attachments from PL/SQLrem Notes: From Oracle8i release 8.1.6 one can send e-mail messagesrem directly from PL/SQL using either the UTL_TCP or UTL_SMTPrem packages. Jserver needs to be installed and configured.rem No pipes or external procedures required.rem Date: 15-MAR-2001rem Author: Virgilio Nunes ([email protected])rem ———————————————————————-
CREATE OR REPLACE PROCEDURE SEND_MAIL (msg_from varchar2 := ‘[email protected]’, —– MAIL BOX SENDING THE EMAILmsg_to varchar2 := ‘[email protected]’, —– MAIL BOX RECIEVING THE EMAILmsg_subject varchar2 := ‘Output file TEST1′, —– EMAIL SUBJECTmsg_text varchar2 := ‘THIS IS THE TEXT OF THE EMAIL MESSAGE.’,v_output1 varchar2 := ‘THIS IS THE TEXT OF THE ATTACHMENT FILE. THIS TEXT SHOULD BE IN A TEXT FILE ATTACHED TO THE EMAIL.’)ISc utl_tcp.connection;rc integer;crlf VARCHAR2(2):= CHR(13)”CHR(10);mesg VARCHAR2( 32767 );BEGINc := utl_tcp.open_connection(’196.35.140.18′, 25); —– OPEN SMTP PORT CONNECTIONrc := utl_tcp.write_line(c, ‘HELO 196.35.140.18′); —– PERFORMS HANDSHAKING WITH SMTP SERVERdbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘EHLO 196.35.140.18′); —– PERFORMS HANDSHAKING WITH SMTP SERVER, INCLUDING EXTRA INFORMATIONdbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘MAIL FROM: ”’msg_from); —– MAIL BOX SENDING THE EMAIL
dbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘RCPT TO: ”’msg_to); —– MAIL BOX RECIEVING THE EMAILdbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘DATA’); —– EMAIL MESSAGE BODY STARTdbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘Date: ”’TO_CHAR( SYSDATE, ‘dd Mon yy hh24:mi:ss’ ));rc := utl_tcp.write_line(c, ‘From: ”’msg_from”’ <'''msg_from'''>‘);rc := utl_tcp.write_line(c, ‘MIME-Version: 1.0′);rc := utl_tcp.write_line(c, ‘To: ”’msg_to”’ <'''msg_to'''>‘);rc := utl_tcp.write_line(c, ‘Subject: ”’msg_subject);rc := utl_tcp.write_line(c, ‘Content-Type: multipart/mixed;’); —– INDICATES THAT THE BODY CONSISTS OF MORE THAN ONE PARTrc := utl_tcp.write_line(c, ‘ boundary=”—–SECBOUND”‘); —– SEPERATOR USED TO SEPERATE THE BODY PARTSrc := utl_tcp.write_line(c, ”); —– INSERTS A BLANK LINE. PART OF THE MIME FORMAT AND NONE OF THEM SHOULD BE REMOVED.rc := utl_tcp.write_line(c, ‘——-SECBOUND’);rc := utl_tcp.write_line(c, ‘Content-Type: text/plain’); —– 1ST BODY PART. EMAIL TEXT MESSAGErc := utl_tcp.write_line(c, ‘Content-Transfer-Encoding: 7bit’);rc := utl_tcp.write_line(c, ”);rc := utl_tcp.write_line(c, msg_text); —– TEXT OF EMAIL MESSAGErc := utl_tcp.write_line(c, ”);rc := utl_tcp.write_line(c, ‘——-SECBOUND’);rc := utl_tcp.write_line(c, ‘Content-Type: text/plain;’); —– 2ND BODY PART.rc := utl_tcp.write_line(c, ‘ name=”Test.txt”‘);rc := utl_tcp.write_line(c, ‘Content-Transfer_Encoding: 8bit’);rc := utl_tcp.write_line(c, ‘Content-Disposition: attachment;’); —– INDICATES THAT THIS IS AN ATTACHMENTrc := utl_tcp.write_line(c, ‘ filename=”Test.txt”‘); —– SUGGESTED FILE NAME FOR ATTACHMENTrc := utl_tcp.write_line(c, ”);rc := utl_tcp.write_line(c, v_output1);rc := utl_tcp.write_line(c, ‘——-SECBOUND–’);rc := utl_tcp.write_line(c, ”);rc := utl_tcp.write_line(c, ‘.’); —– EMAIL MESSAGE BODY ENDdbms_output.put_line(utl_tcp.get_line(c, TRUE));rc := utl_tcp.write_line(c, ‘QUIT’); —– ENDS EMAIL TRANSACTIONdbms_output.put_line(utl_tcp.get_line(c, TRUE));utl_tcp.close_connection(c); —– CLOSE SMTP PORT CONNECTIONEXCEPTIONwhen others thenraise_application_error(-20000, SQLERRM);END;/
Whether GL Period is open or not as of sysdate?
select gls.name, gps.closing_status fromapps.GL_PERIOD_STATUSES gps, gl_sets_of_books gls
where 1=1and gps.start_date <= sysdateand gps.end_date >= sysdateand gps.set_of_books_id = gls.set_of_books_idand gps.set_of_books_id >= &Set_of_books_idand gps.application_id=&Application_id — 101 = GL, 222 = ARand gls.chart_of_accounts_id=&chart_of_accounts_idand gls.name in ( ‘&OperatingUnit’ )
GL Handy SQL’s – How do I obtain CCID ( code combination id) / Chart of Account data for General Ledger
SELECTsubstr(gl.code_combination_id,1,5) ccid,substr(gl.segment1,1,5) ,substr(gl.segment2,1,8) ,substr(gl.segment3,1,5) ,substr(gl.segment4,1,5) ,substr(gl.segment5,1,5) ,substr(gl.segment6,1,5) ,substr(gl.segment7,1,5) ,substr(gl.segment8,1,5)FROM gl.gl_code_combinations glORDER BY code_combination_id;
How TO find your current GL Period END DATESELECT a.END_DATEFROM GL_PERIOD_STATUSES aWHERE a.application_id = ‘222′AND a.closing_status = ‘O’AND a.start_date = (SELECT max(b.start_date)FROM gl_period_statuses bWHERE b.application_id = ‘222′AND b.closing_status = ‘O’);
What is my current GL Period?select max(gl_date) from ra_cust_trx_line_gl_dist_all;
Get Operating Unit & Legal Entity
Following script extracts the operating unit and legal entities from oracle applications
————————————————————————-— Author : ————————————————————————-SELECThr.name operating_unit,hr.organization_id org_id,
le.name legal_entity_name,decode(ar.set_of_books_id,‘-1′,‘No’,NULL,‘No’,‘Yes’) system_option_definedFROMhr_operating_units hr,hr_all_organization_units_tl le,ar_system_parameters_all arWHERE le.organization_id = to_number(hr.legal_entity_id)AND le.LANGUAGE = userenv(‘LANG’)AND hr.organization_id = ar.org_id(+)ORDER BY 2;
Profile option check – Initialization SQL Statement – Oracle
————————————————————————-— Author : Gopal————————————————————————-select po.profile_option_name “NAME”,po.USER_PROFILE_OPTION_NAME,decode(to_char(pov.level_id),‘10001′, ‘SITE’,‘10002′, ‘APP’,‘10003′, ‘RESP’,‘10005′, ‘SERVER’,‘10006′, ‘ORG’,‘10004′, ‘USER’, ‘???’) “LEV”,decode(to_char(pov.level_id),‘10001′, ”,‘10002′, app.application_short_name,‘10003′, rsp.responsibility_key,‘10005′, svr.node_name,‘10006′, org.name,‘10004′, usr.user_name,‘???’) “CONTEXT”,pov.profile_option_value “VALUE”from FND_PROFILE_OPTIONS_VL po,FND_PROFILE_OPTION_VALUES pov,fnd_user usr,fnd_application app,fnd_responsibility rsp,fnd_nodes svr,hr_operating_units orgwhere po.USER_PROFILE_OPTION_NAME like ‘%SQL%Statement%’and pov.application_id = po.application_idand pov.profile_option_id = po.profile_option_idand usr.user_id (+) = pov.level_valueand rsp.application_id (+) = pov.level_value_application_idand rsp.responsibility_id (+) = pov.level_valueand app.application_id (+) = pov.level_valueand svr.node_id (+) = pov.level_valueand org.organization_id (+) = pov.level_valueorder by “NAME”, pov.level_id, “VALUE”;
List Reponsibilities for an user I often get this issue to find out list of responsibilities assigned to an user, mainly to review the SOX controls or to enable new responsibilities.Lazy enough to go to System Administrator screen to query it. I always keep the TOAD open session and it is easy to grab the details using this sql.
————————————————————————-— Author : Gopal————————————————————————-SELECT fu.user_name,frt.RESPONSIBILITY_NAME, fu.user_id,furg.responsibility_idFROMfnd_user_resp_groups furg,FND_RESPONSIBILITY fr,fnd_responsibility_tl frt,fnd_user fuWHERE fu.user_name =upper( ‘&username’)AND fu.user_id = furg.user_idAND furg.responsibility_id = fr.RESPONSIBILITY_IDAND frt.responsibility_id = fr.RESPONSIBILITY_IDORDER BY 1
List the responsibilities that can run a given concurrent program
————————————————————————-— Author : Gopal————————————————————————-
SELECT fr.responsibility_name RN ,fcpt.user_concurrent_program_nameFROM fnd_request_groups frg,fnd_request_group_units frgu,fnd_concurrent_programs fcp,fnd_concurrent_programs_tl fcpt,fnd_responsibility_vl frWHERE frgu.request_unit_type = ‘P’and UPPER(fcpt.user_concurrent_program_name) = UPPER(’Journal Entries Report’)AND frgu.request_group_id = frg.request_group_idAND frgu.request_unit_id = fcp.concurrent_program_idAND fr.request_group_id = frg.request_group_idAND fcp.CONCURRENT_PROGRAM_ID = fcpt.CONCURRENT_PROGRAM_IDORDER BY 1
How to Verify a Patch applied?
Just run this sample sql changing the patch number (3061831) in sqlplus or Toad.
SELECT DISTINCT rpad(a.bug_number,11)” rpad(e.patch_name,11)”rpad(trunc(c.end_date),12) ”rpad(b.applied_flag,4)FROMad_bugs a,ad_patch_run_bugs b,ad_patch_runs c,ad_patch_drivers d,ad_applied_patches eWHERE a.bug_id = b.bug_idAND b.patch_run_id = c.patch_run_idAND c.patch_driver_id = d.patch_driver_idAND d.applied_patch_id = e.applied_patch_idAND a.bug_number IN (‘3061831′)ORDER BY 1 DESC ;
Set an OPERATING UNIT
In oracle applications, you have developed pl/sql code or sql code listed. If you are running as apps and sending the query with _ALL table, you get the data. However, if your query is a copy and paste from forms or reports that uses oracle applications view, you may not get the results. The reason is that these views and linked with operating unit specific. If you need the same results what you are getting when you are inside some operation unit, you need to set the operating unit in oracle environment profile. This can be archived by setting dbms_application_info.set_client_info as given below:
–– Set an OPERATING UNIT–begindbms_application_info.set_client_info(204);end;
The user guide gives “Your applications should set the name of the module and name of the action automatically each time a user enters that module. The module name could be the name of a form in an Oracle Forms application, or the name of the code segment in an Oracle Precompilers application. The action name should usually be the name or description of the current transaction within a module>”