Sunday, August 18, 2013

Using Connect By in SQL

Connect By In SQL.


example :- i have sting like 'aactranportes@uol.com.br; ; d.ojea@seafrigo.com; a.ferrao@seafrigo.com'.
i want to split these email properly into rows.


select *
from (
SELECT level,
trim(substr(email,
instr(';' || email || ';', ';', 1, rownum),
instr(';' || email || ';', ';', 1, rownum + 1) -
instr(';' || email || ';', ';', 1, rownum) - 1)) email
FROM (select 'aactranportes@uol.com.br; ; d.ojea@seafrigo.com; a.ferrao@seafrigo.com' email from dual)
CONNECT BY LEVEL <= 10) wrk
where nvl(length(email),0) > 0



Same convert into columnsss



select email,
(substr(email,1,instr(email,';',1)-1)) email1,
(substr(email,instr(email,';',1)+1,instr(email,';',1,2)-instr(email,';',1)-1)) email2,
(substr(email,instr(email,';',1,2)+1)) email3
from
(select 'aactranportes@uol.com.br;d.ojea@seafrigo.com;a.ferrao@seafrigo.com' email from dual)

Monday, August 12, 2013

SQL to identify the query being executed by the concurrent program currently

How do you identify which SQL is running behind the concurrent program at a particular instant?
   
The SQL given below lists out the request id, SID, concurrent program name and the concurrent program start time currently being executed in the instance.

  SELECT fcr.request_id,
                  
vs.SID,
                  
fcpt.user_concurrent_program_name,
         TO_CHAR (fcr.actual_start_date,
                  'mm/dd/rrrr hh24:mi:ss') time_started
    FROM fnd_concurrent_requests fcr,

                  
fnd_concurrent_programs_tl fcpt,
                  
v$session vs,
                  
v$process vp
   WHERE fcpt.concurrent_program_id = fcr.concurrent_program_id

     AND fcpt.application_id = fcr.program_application_id
     AND fcpt.LANGUAGE 'US'
     AND phase_code 'R'
     AND status_code 'R'
     AND vs.audsid = oracle_session_id
     AND vp.addr = vs.paddr

ORDER BY actual_start_date;



Get the SID for the concurrent program for which you want to see the SQL currently being executed and pass it to the SQL below.

  SELECT sql_text
    FROM SYS.v_$sqltext
   WHERE hash_value = (SELECT sql_hash_value
                         FROM SYS.v_$session
                        WHERE SID = &v_sid)

ORDER BY piece;

Get Oracle Application's URL from backend

Most of the times, we tend to forget to add the URL of the Oracle instances and we search where to find it.

Well instead of searching through papers or files you can directly execute the query given below to get the URL of the instance.
SELECT home_url
   
FROM icx_parameters;

APIs to Delete Concurrent Program

Many a times we had defined concurrent program wrongly and wondered how to delete it.
 
Well Oracle does provide an API to accomplish it.

API to delete the program
fnd_program.delete_program('Short Name', 'Application');

API to delete the executable 
fnd_program.delete_executable('Short Name', 'Application');
Do remember to issue the commit after you are done.

Saturday, August 10, 2013

Oracle Application – Top useful SQL Queries

Find reps name with conc prg name
---------------

SELECT responsibility_name
FROM fnd_responsibility_vl
WHERE request_group_id IN
  (SELECT request_group_id
  FROM fnd_request_group_units
  WHERE request_unit_id IN
    (SELECT concurrent_program_id
    FROM fnd_concurrent_programs_tl
    WHERE user_concurrent_program_name LIKE 'XXAP - Remittance Advice Send Mail Supplier'
    )
  )


Query 1: Select responsibility name along with application
name
SELECT application_short_name ,
frt.responsibility_id, frt.responsibility_name
FROM apps.fnd_responsibility_tl frt , fnd_application fa
WHERE fa.application_id = frt.application_id


Query 2: Get Menu name for Responsibility ID , You can find
out responsibility_id from Query 1
SELECT DISTINCT a.responsibility_name, c.user_menu_name
FROM apps.fnd_responsibility_tl a,
apps.fnd_responsibility b,
apps.fnd_menus_tl c,
apps.fnd_menus d,
apps.fnd_application_tl e,
apps.fnd_application f
WHERE a.responsibility_id(+) = b.responsibility_id
AND a.responsibility_id = &resp_id
AND b.menu_id = c.menu_id
AND b.menu_id = d.menu_id
AND f.application_id = b.application_id
AND a.language = 'US';


Query 3: Get User name and related assigned responsibilities
SELECT distinct u.user_id, u.user_name user_name,
r.responsibility_name responsiblity,
a.application_name application
FROM fnd_user u,
fnd_user_resp_groups g,
fnd_application_tl a,
fnd_responsibility_tl r
WHERE g.user_id(+) = u.user_id
AND g.responsibility_application_id = a.application_id
AND a.application_id = r.application_id
AND g.responsibility_id = r.responsibility_id
order by 1;


Query 4: Get Request Group associate with Responsibility
Name
SELECT responsibility_name responsibility,
request_group_name,
frg.description
FROM fnd_request_groups frg, fnd_responsibility_vl frv
WHERE frv.request_group_id = frg.request_group_id
ORDER BY responsibility_name


Query 5: Gets Form personalization listing
Personalization is feature available in 11.5.10.X. For More
detail on form Personalization Use Following Tables (Rule_id)
is reference key for these tables

applsys.fnd_form_custom_actions,
applsys.fnd_form_custom_scopes
SELECT ffft.user_function_name “User Form Name”,
ffcr.SEQUENCE,
ffcr.description, ffcr.rule_type, ffcr.enabled, ffcr.trigger_event,
ffcr.trigger_object, ffcr.condition, ffcr.fire_in_enter_query
FROM fnd_form_custom_rules ffcr, fnd_form_functions_vl ffft
WHERE ffcr.ID = ffft.function_id
ORDER BY 1;


Query 6: Query to view the patch level status of all modules
SELECT a.application_name,
DECODE (b.status, ‘I’, ‘Installed’, ‘S’, ‘Shared’, ‘N/A’)
status,
patch_level
FROM apps.fnd_application_vl a,
apps.fnd_product_installations b
WHERE a.application_id = b.application_id;


Query 7: SQL to view all request who have attached to a
responsibility
SELECT responsibility_name , frg.request_group_name,
fcpv.user_concurrent_program_name, fcpv.description
FROM fnd_request_groups frg,
fnd_request_group_units frgu,
fnd_concurrent_programs_vl fcpv,
fnd_responsibility_vl frv
WHERE frgu.request_unit_type = ‘P’
AND frgu.request_group_id = frg.request_group_id
AND frgu.request_unit_id = fcpv.concurrent_program_id
AND frv.request_group_id = frg.request_group_id


ORDER BY responsibility_name;
Query 8: SQL to view all requests who have attached to a
responsibility
SELECT responsibility_name , frg.request_group_name,
fcpv.user_concurrent_program_name, fcpv.description
FROM fnd_request_groups frg,
fnd_request_group_units frgu,
fnd_concurrent_programs_vl fcpv,
fnd_responsibility_vl frv
WHERE frgu.request_unit_type = ‘P’
AND frgu.request_group_id = frg.request_group_id
AND frgu.request_unit_id = fcpv.concurrent_program_id
AND frv.request_group_id = frg.request_group_id
ORDER BY responsibility_name;


Query 9: SQL to view all types of request Application wise
SELECT fa.application_short_name,
fcpv.user_concurrent_program_name,
description,
DECODE (fcpv.execution_method_code,
‘B’, ‘Request Set Stage Function’,
‘Q’, ‘SQL*Plus’,
‘H’, ‘Host’,
‘L’, ‘SQL*Loader’,
‘A’, ‘Spawned’,
‘I’, ‘PL/SQL Stored Procedure’,
‘P’, ‘Oracle Reports’,
‘S’, ‘Immediate’,
fcpv.execution_method_code
) exe_method,
output_file_type, program_type, printer_name,
minimum_width,
minimum_length, concurrent_program_name,
concurrent_program_id
FROM fnd_concurrent_programs_vl fcpv, fnd_application fa
WHERE fcpv.application_id = fa.application_id
ORDER BY description;


Query 10: SQL to view concurrent request processing time,
quite useful
SELECT f.request_id , pt.user_concurrent_program_name
user_concurrent_program_name
, f.actual_start_date actual_start_date
, f.actual_completion_date actual_completion_date,
floor(((f.actual_completion_datef.
actual_start_date)*24*60*60)/3600)
|| ‘ HOURS ‘ ||
floor((((f.actual_completion_datef.
actual_start_date)*24*60*60) -
floor(((f.actual_completion_datef.
actual_start_date)*24*60*60)/3600)*3600)/60)
|| ‘ MINUTES ‘ ||
round((((f.actual_completion_datef.
actual_start_date)*24*60*60) -
floor(((f.actual_completion_datef.
actual_start_date)*24*60*60)/3600)*3600 -
(floor((((f.actual_completion_datef.
actual_start_date)*24*60*60) -
floor(((f.actual_completion_datef.
actual_start_date)*24*60*60)/3600)*3600)/60)*60) ))
|| ‘ SECS ‘ time_difference
,
DECODE(p.concurrent_program_name,’ALECDC’,p.concurrent_program_name||’
['||f.description||']‘,p.concurrent_program_name)
concurrent_program_name
,
decode(f.phase_code,’R',’Running’,'C’,'Complete’,f.phase_code)
Phase
, f.status_code
FROM apps.fnd_concurrent_programs p
, apps.fnd_concurrent_programs_tl pt
, apps.fnd_concurrent_requests f
WHERE f.concurrent_program_id = p.concurrent_program_id
and f.program_application_id = p.application_id
and f.concurrent_program_id = pt.concurrent_program_id
and f.program_application_id = pt.application_id
AND pt.language = USERENV(‘Lang’)
and f.actual_start_date is not null
ORDER by f.actual_completion_date-f.actual_start_date desc;

What is cost center used for in Oracle EBS?

Cost center is one of the accounting flexfield components in Oracle General Ledger, which is part of Oracle Financial modules in Oracle EBS
The accounting flexfield may have segments like:
1 Company
2 Dept......[cost Center]
3 Account
4 Sub-Account
5 Product

Cost centers indicate functional areas of your organization, such as Accounting, Facilities, Shipping, and so on.....

Oracle Assets Module and Oracle Projects Module requires to qualify a segment as cost center in your account

Benefits are you can group your Assets by Cost Center or Department, ascertain project cost for a particular project based on cost centers and so on...


 Cost center is a department in an Organization.
Then again it depends on your line of business. LOB.
For example if your Operating units are Vision Ops US and Vision Ops UK you will have different cost centers tied to these two units.

A cost center will depend on your company and how it views things. Keep in mind this is still part of the g/l account accounting flexfield. A key flexfield will contain its own value set, independent of other Oracle tables. Now you may create values in the value set for the segment that is the cost center that may correspond to, say, your HR Organization untis, but that will be only because you created them that way. If you add a new HR Unit, it will NOT show in the cost center value set until someone goes into that maintenance and adds the value there as well. Just have to understand that relationship.

Subquries

Types of Subquries:-

     Single Row sub queries: - return zero rows or one row to the outer SQL stmt.There is a special case of single row that contains exactly one column, this type of sub queries are called as scalar sub query.

Multiple row sub queries: - return one or more rows to the outer SQL statement

In addition there are three subtypes of sub queries that may return single row or multiple rows.

Multiple – column sub queries :- return more than one column to the outer SQL stmt

Correlated sub queries :- reference one or more columns in the outer SQL statement .These are called correlated sub queries because they are related to the outer SQL stmt through the same columns.

Nested sub queries :-  are placed within another sub query. you can nest sub queries to depth of 255.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

     Single Row sub queries: -
                              
1)      select name,salary from emp where empno = (select empno from emp where name = ‘RAJESH’);
2)      select product_id,name ,price from products where price > (select avg(price) from products );
3)      select product_type_id,avg(price) from products group by product_type_id having avg(price) < (select max(avg)price)) from products group by product_type_id order by product_type_id;
4)      sub queries in from clause(Inline Queries)
        
        select product_id from (select procust_id from products where product_id <3);

        select prds.product_id,price,purchase_data.product_count from products prds,
                  (select product_id ,count(product_id) product_count from purchases
                    Group by product_id) purchase_data
        Where prds.product_id =  purchase_data.prodcut_id;

Here the sub query is just another source of data to the from clause of the outer query.

Errors you might encounter

    Single row sub queries may return maximum of one row . If your sub query return one row you will get the following error

ORA-01427 single-row subquery return more than one row.

    Sub queries may not contain an order by clause . instead any ordering must be done in the outer query .for example

Select product_id ,  name , price fromm products where price > (select avg(price) frin products )order by product_id desc;



Multiple row sub queries

     You use a multiple – row sub query to return one or more rows to outer SQL stmt.TO handle this case your outer query may use IN,ANY,or ALL operator.you can also use the EXISTS operator to check of a value is in a list returned by a correlated sub query.

IN:-

1)   Select product_id,name from products where product_id IN (select product_id from products from products where name like ‘%Laptop%’);

 2)  Select product_id,name from products where product_id NOT IN (select product_id from products from products where name like ‘%Laptop%’);

ANY:-

1)      select empno,nme from emp where salary < ANY (select low_salary from salary_grades);

      ALL:-

         Select empno,name form emp where salary > ALL(select high_salary form salary_grades);

        Results :-  no rows selected


        Multiple Column sub queries :-
 
             Select product_id ,product_type_id name ,price from products where (product_id,price ) IN    (select product_id,MIN(price) from products group by product_type_id);


     Note that sub query returns more than one column .


Correlated Subquries:-

     Correlated sub queries references one or more columns in the outer SQL stmt.

You typically use a correlated sub queries when you need an answer to a question that depends on a values in each row contained in an outer query.For example you might want to see whether there is a relationship between the data but don’t care how many rows are returned by the sub query.
That is you just wan tot check whether any rows are retrned but you don’t care how many.

    Correlated sub query us run in once for each row in the outer query: this is different from non – correlated sub query , which is run once prior to running the outer query.in addition a correlated sub query can resolve null values.


Select product_id ,produt_type_id,name,price
From products outer
Where price >
   (select avg(price) from products inner where inner.product_type_id = outer.product_type_id);

Using Exists ,Not Exists

   Select empno,name
   From emp
    Where exists
               (select emono from emp inner
                 Where inner.manager_num = outer.empno);


Or

   Select empno,name
   From emp
    Where exists
               (select 1 from emp inner
                 Where inner.manager_num = outer.empno);


Exists and Not Exists Versus In and NOT IN


    Exists is different from IN : Exists checks just for the existence of rows ,where as IN check for actual actualvalues

  Exists typically offers better performance than IN with subqueries ,therefore you should use exists rather than IN wherever possible.

You should be careful when using Exists /Not Exists and IN  /Not IN . When a list of values contains a null value ,Not exists returns true ,but Not In returns false.


For example :-

Query to fetch the product types that don’t have any products of that type in the products table.


Select product_type_id,name
From product_type outer
Where Not Exists
( select 1 from products inner
    Where inner.product_type_id = outer.product_type_id);


Product_type_id       name
---------------------      -----------------------
5              Computers


Notice one row is returned one row
When you use Not in :

Select product_type_id,name
From product_type outer
Where Not IN
( select product_type_id  from products);

No rows returned


Because the subquery returns a list of product_id values,one of which is null.


When can overcome this problem using NVL

Select product_type_id,name
From product_type outer
Where Not IN
( select nvl(product_type_id ,0) from products);


Product_type_id       name
---------------------      -----------------------
5          Computers



Nested Subquereis


  You can nest sub queries inside the other sub queries to depth of 255.


Select product_type_id,avg(price)
From products
Group by product_type_id
Having avg(price) <
(select max(avg(price))
 From products
Where product_type_id in
   (select product_type_id
    From purchase
Where quantity >1
Group by product_typ_id)
Order by product_typ_id;


We can write upodate and delete statements containing subqueries

  Update emp
  Set salary =
       (select avg(high_salary)
          From salary_grades)
Where empno =4;

   Delete from emp
Where salary >
   Select avg(slary) from salary_grades);

  

Friday, August 9, 2013

SQL Loader Part 2

SQL LOADER is a very powerful tool that lets you load data from a delimited or position based data file into Oracle tables. We have received many questions regarding SQL LOADER features from many users. Here is the brief explanation on the same. 
Please note that the basic knowledge of SQL LOADER is required to understand this article.
This article covers the below topics:
1. Load multiple data files into a single table
2. Load a single data file into multiple tables
3. Skip a column while loading using “FILLER” and Load field in the delimited data file into two different columns in a table using “POSITION”
4. Usage of BOUNDFILLER
5. Load the same record twice into a single table
6. Using WHEN to selectively load the records into the table
7. Run SQLLDR from SQL PLUS
8. Default path for Discard, bad and log files
1) Load multiple files into a single table:
SQL LOADER lets you load multiple data files at once into a single table. But all the data files should be of the same format.
Here is a working example:
Say you have a table named EMP which has the below structure:
ColumnData Type
emp_numNumber
emp_nameVarchar2(25)
department_numNumber
department_nameVarchar2(25)

You are trying to load the below comma delimited data files named eg.dat and eg1.dat:
eg.dat:
7369,SMITH,7902,Accounting
7499,ALLEN,7698,Sales
7521,WARD,7698,Accounting
7566,JONES,7839,Sales
7654,MARTIN,7698,Accounting

eg1.dat:
1234,Tom,2345,Accounting
3456,Berry,8976,Accounting

The Control file should be built as below:

LOAD DATA
INFILE ‘eg.dat’ — File 1
INFILE ‘eg1.dat’ — File 2
APPEND
INTO TABLE emp
FIELDS TERMINATED BY “,”
( emp_num, emp_name, department_num, department_name )

2) Load a single file into multiple tables:
SQL Loader lets you load a single data file into multiple tables using “INTO TABLE” clause.
Here is a working example:
Say you have two tables named EMP and DEPT which have the below structure:
TableColumnData Type
EMPemp_numNumber
EMPemp_nameVarchar2(25)
DEPTdepartment_numNumber
DEPTdepartment_nameVarchar2(25)

You are trying to load the below comma delimited data file named eg.dat which has columns Emp_num and emp_name that need to be loaded into table EMP and columns department_num and department_name that need to be loaded into table DEPT using a single CTL file here.
eg.dat:
7369,SMITH,7902,Accounting
7499,ALLEN,7698,Sales
7521,WARD,7698,Accounting
7566,JONES,7839,Sales
7654,MARTIN,7698,Accounting

The Control file should be built as below:
LOAD DATA
INFILE ‘eg.dat’
APPEND
INTO TABLE emp
FIELDS TERMINATED BY “,”
( emp_num, emp_name )
INTO TABLE dept
FIELDS TERMINATED BY “,”
(department_num, department_name)
You can further use WHEN clause to selectively load the records into the tables which will be explained later in this article.

3) Skip a column while loading using “FILLER” and Load field in the delimited data file into two different columns in a table using “POSITION”
SQL LOADER lets to skip unwanted fields in the data file by using the “FILLER” clause. Filler was introduced in Oracle 8i.
SQL LOADER also lets you load the same field into two different columns of the table.
If the data file is position based, loading the same field into two different columns is pretty straight forward. You can use Position (start_pos:end_pos) keyword
If the data file is a delimited file and it has a header included in it, then this can be achieved by referring the field preceded with “:” eg description “(:emp_name)”.
If the data file is delimited file without a header included in it, Position (start_pos:end_pos) or “(:field)” will not work. This can be achieved using POSITION (1) clause which takes you to the beginning of the record.

Here is a Working Example:
The requirement here is to load the field emp_name in the data field into two columns – emp_name and description of the table EMP. Here is the Working Example:

Say you have a table named EMP which has the below structure:
ColumnData Type
emp_numNumber
emp_nameVarchar2(25)
descriptionVarchar2(25)
department_numNumber
department_nameVarchar2(25)

You are trying to load the below comma delimited data file named eg.dat which has 4 fields that need to be loaded into 5 columns of the table EMP.
eg.dat:
7369,SMITH,7902,Accounting
7499,ALLEN,7698,Sales
7521,WARD,7698,Accounting
7566,JONES,7839,Sales
7654,MARTIN,7698,Accounting

Control File:
LOAD DATA
INFILE ‘eg.dat’
APPEND
INTO TABLE emp
FIELDS TERMINATED BY “,”
(emp_num,
emp_name,
desc_skip FILLER POSITION(1),
description,
department_num,
department_name)
Explanation on how SQL LOADER processes the above CTL file:
 The first field in the data file is loaded into column emp_num of table EMP
 The second field in the data file is loaded into column emp_name of table EMP
 The field desc_skip enables SQL LOADER to start scanning the same record it is at from the beginning because of the clause POSITION(1) . SQL LOADER again reads the first delimited field and skips it as directed by “FILLER” keyword.
 Now SQL LOADER reads the second field again and loads it into description column of the table EMP.
 SQL LOADER then reads the third field in the data file and loads into column department_num of table EMP
 Finally the fourth field is loaded into column department_name of table EMP.
4) Usage of BOUNDFILLER
BOUNDFILLER is available with Oracle 9i and above and can be used if the skipped column’s value will be required later again.

Here is an example:
The requirement is to load first two fields concatenated with the third field as emp_num into table emp and Fourth field as Emp_name

Data File:
1,15,7369,SMITH
1,15,7499,ALLEN
1,15,7521,WARD
1,18,7566,JONES
1,20,7654,MARTIN

The requirement can be achieved using the below Control File:
LOAD DATA
INFILE ‘C:\eg.dat’
APPEND
INTO TABLE EMP
FIELDS TERMINATED BY “,”
(
Rec_skip BOUNDFILLER,
tmp_skip BOUNDFILLER,
Emp_num “(:Rec_skip||:tmp_skip||:emp_num)”,
Emp_name
)

5) Load the same record twice into a single table:
SQL Loader lets you load record twice using POSITION clause but you have to take into account whether the constraints defined on the table allow you to insert duplicate rows.

Below is the Control file:

LOAD DATA
INFILE ‘eg.dat’
APPEND
INTO TABLE emp
FIELDS TERMINATED BY “,”
( emp_num, emp_name, department_num, department_name )
INTO TABLE emp
FIELDS TERMINATED BY “,”
(emp_num POSITION(1),emp_name,department_num,department_name)

SQL LOADER processes the above control file this way:
First “INTO TABLE” clause loads the 4 fields specified in the first line of the data file into the respective columns (emp_num, emp_name, department_num, department_name)
Field scanning does not start over from the beginning of the record when SQL LOADER encounters the second INTO TABLE clause in the CTL file. Instead, scanning continues where it left off. Statement “emp_num POSITION(1)” in the CTL file forces the SQL LOADER to read the same record from the beginning and loads the first field in the data file into emp_num column again. The remaining fields in the first record of the data file are again loaded into respective columns emp_name, department_num, department_name. Thus the same record can be loaded multiple times into the same table using “INTO TABLE” clause.


6) Using WHEN to selectively load the records into the table
WHEN clause can be used to direct SQL LOADER to load the record only when the condition specified in the WHEN clause is TRUE. WHEN statement can have any number of comparisons preceded by AND. SQL*Loader does not allow the use of OR in the WHEN clause.
Here is a working example which illustrates how to load the records into 2 tables EMP and DEPT based on the record type specified in the data file.
The below is delimited data file eg.dat which has the first field as the record type. The requirement here is to load all the records with record type = 1 into table EMP and all the records with record type = 2 into table DEPT and record with record type =3 which happens to be the trailer record should not be loaded.
1,7369,SMITH
2,7902,Accounting
1,7499,ALLEN
2,7698,Sales
1,7521,WARD
2,7698,Accounting
1,7566,JONES
2,7839,Sales
1,7654,MARTIN
2,7698,Accounting
3,10
Control File:
LOAD DATA
INFILE ‘eg.dat’
APPEND
INTO TABLE emp
WHEN (01) = ’1′
FIELDS TERMINATED BY “,”
( rec_skip filler POSITION(1),emp_num , emp_name )
INTO TABLE dept
WHEN (01) = ’2′
FIELDS TERMINATED BY “,”
(rec_skip filler POSITION(1),department_num,
department_name )