Getting manager & managers manager number in oracle - oracle

I have below table in oracle
EMPNO ENAME MGR
1 A 1
2 B 1
3 C 2
4 D 3
5 F 1
6 G 3
7 H 6
I need to pass a EMPNO and it should give me manger id and if manager has another manager it should give me there id's too in the same field.
For example, If I pass empno = 7 then the output should be 6,3,2,1.

You can use the connect by syntax to create a hierarchical query:
SELECT mgr
FROM emp
START WITH empno = 7
CONNECT BY PRIOR empno = mgr

Here is the query, I used finally for the actual results
SELECT ENAME,
CONNECT_BY_ISCYCLE Cycle,
LEVEL,
SYS_CONNECT_BY_PATH(ENAME, '/') Path
FROM EMP_DEMO
START WITH empno = '7'
CONNECT BY NOCYCLE PRIOR MGR = EMPNO;
You always have to take the max level record.

Related

PL/SQL looping 'back' through the records

I have a problem i hope you can help to resolve.
I have a table named PRODUCT:
Product_ID NOT NULL NUMBER(10)
TARGET_PRODUCT VARCHAR2(10)
SOURCE_PRODUCT VARCHAR2(10)
So each target_product made out of source_product(except the first one - first one just has target_product and source_product is null)
I need to find the fist source_product for given target_product.
I need to go 'back' in a loop until source product is null.
Is there a solution for this scenario?
Thanks in advance
It is not a loop you need, but hierarchical query. Have a look at the following example based on Scott's EMP table.
This is its contents; employees are displayed hierarchically, showing who's whose boss:
SQL> select level,
2 lpad(' ', level * 2, ' ') || e.ename name
3 from emp e
4 start with e.mgr is null
5 connect by prior e.empno= e.mgr;
LEVEL NAME
---------- ---------------
1 KING
2 JONES
3 SCOTT
4 ADAMS
3 FORD
4 SMITH
2 BLAKE
3 ALLEN
3 WARD
3 MARTIN
3 TURNER
3 JAMES
2 CLARK
3 MILLER
14 rows selected.
SQL>
As you want to start from the middle of the table (for example, starting from SMITH), you'd "reverse" it:
SQL> select level lvl,
2 lpad(' ', level * 2, ' ') || e.ename name
3 from emp e
4 start with e.ename = 'SMITH'
5 connect by prior e.mgr= e.empno;
LVL NAME
---------- ---------------
1 SMITH
2 FORD
3 JONES
4 KING
SQL>
Finally, using that query as a CTE (or a subquery, if your Forms version doesn't support CTEs), fetch the one whose name has the highest level:
SQL> with temp as
2 (select level lvl,
3 lpad(' ', level * 2, ' ') || e.ename name
4 from emp e
5 start with e.ename = 'SMITH'
6 connect by prior e.mgr= e.empno
7 )
8 select trim(t.name) name
9 from temp t
10 where t.lvl = (select max(t1.lvl) from temp t1);
NAME
---------------
KING
SQL>
Or, even better, using connect_by_isleaf:
SQL> select e.ename name
2 from emp e
3 where connect_by_isleaf = 1
4 start with e.ename = 'SMITH'
5 connect by prior e.mgr= e.empno;
NAME
---------------
KING
SQL>
You may try this, it will return the base target_product for a given target_product:
select * from (
select PRODUCT_ID, TARGET_PRODUCT, SOURCE_PRODUCT
from PRODUCT
start with target_product = '<your target product>'
connect by prior SOURCE_PRODUCT = TARGET_PRODUCT
)
where SOURCE_PRODUCT is null;

Hierarchical Query CONNECT BY Oracle

I am trying to implement the Connect By query in oracle. Trying to understand how it works. So I have a simple table
which looks likes:
empno ename mno
1 KS null
2 AB 2
3 BC 1
4 TR 3
5 QE 2
6 PL 3
7 LK 6
The Query
SELECT empno, ename, mno
FROM test
START WITH ename = 'LK'
CONNECT BY PRIOR empno = mno;
So when the name is LK I should get the following parent/child rows LK>PL>BC>KS.
The SQLFIDDLE But I am not getting the correct results. What I am doing wrong ?
No, you should not.
LK's parent is PL. PL's parent is BC. BC's parent is KS. KS has no parent. When you're trying to start tree from LK, you get all it's children - none, because there are no records with mno = 7.
You muddled parent-child order in your query. If you wish to unwind the three from leaf to root, you should ask
SELECT empno, ename, mno
FROM test
START WITH ename = 'LK'
CONNECT BY empno = PRIOR mno;
If you wish to see the tree into the natural order, you should to ask
SELECT empno, ename, mno
FROM test
START WITH mno is null
CONNECT BY PRIOR empno = mno;

Update Statement with two tables -Oracle

I have two tables and I need to Update the second table with a value from first table based on a common column.
I used the below statement
UPDATE emp
2 SET ename = ( SELECT dname
3 FROM dept
4 WHERE emp.deptno = dept.deptno)
5 WHERE EXISTS
6 ( SELECT dname
7 FROM dept
8 WHERE emp.deptno = dept.deptno);
But am getting the error
ORA-01427 - Single row subquery returns more than one row.
Can you plese help me out?
SELECT dname
FROM dept
WHERE emp.deptno = dept.deptno
query must return single record.
check with
SELECT count(*), dname
FROM dept
group by dname
having count(*) > 1
order by 1 desc
or use
SELECT dname
FROM dept
WHERE emp.deptno = dept.deptno
and rownum = 1
You need to check if 1st subquery returns only 1 value bcz if this subquery returns more then 1 row you want to update 1 field ename with 2 values from row and that's why i guess you have this error
Your subquery to dept table is probably not returning one row. Add min or max operation to get one row from dept for each row from emp. Each setting value must be nonambigous.
UPDATE emp
SET ename = ( SELECT min dname
FROM dept
WHERE emp.deptno = dept.deptno)
WHERE EXISTS
( SELECT dname
FROM dept
WHERE emp.deptno = dept.deptno);
Remark1: in default SCOTT schema deptno is primary key, so no error would be encountered.
Remark2: shouldn't your question to be placed in serverfault.com?

Is this a right query? If it is what does it mean

I was given a query to explain. Could someone please explain it to me:
select j.ip_num from
jobs j, address a
where j.jobtype='C' and
a.sel_code(+)='H' and
j.ip_num=a.ip_num and
a.ip_num is null order by a.ip_num
That query selects every JOB.IP_NUM which doesn't have a matching ADDRESS record or where the matching ADDRESS record has a SEL_CODE not equal to 'H'.
The (+) is Oracle's old outer join syntax. It is the only OUTER JOIN syntax supported in versions of Oracle before 9i.
In this query we get one row for every row in EMP which matches a department, plus a row for the DEPTNO=40, which has no employees:
SQL> select d.dname
2 , e.ename
3 from dept d
4 , emp e
5 where d.deptno = e.deptno(+)
6 /
DNAME ENAME
-------------- ----------
ACCOUNTING SCHNEIDER
ACCOUNTING BOEHMER
ACCOUNTING KISHORE
RESEARCH ROBERTSON
RESEARCH KULASH
RESEARCH GASPAROTTO
RESEARCH RIGBY
RESEARCH CLARKE
SALES HALL
SALES CAVE
SALES SPENCER
SALES BILLINGTON
SALES PADFIELD
SALES VAN WIJK
SALES KESTELYN
SALES LIRA
OPERATIONS PSMITH
HOUSEKEEPING VERREYNNE
HOUSEKEEPING FEUERSTEIN
HOUSEKEEPING PODER
HOUSEKEEPING TRICHLER
COMMUNICATIONS
22 rows selected.
SQL>
Now, if we put an additional filter on the EMP table like this, we simply get one record for each Department, because only one record in EMP now matches:
SQL> select d.dname
2 , e.ename
3 from dept d
4 , emp e
5 where d.deptno = e.deptno(+)
6 and e.ename(+) = 'CAVE'
7 /
DNAME ENAME
-------------- ----------
ACCOUNTING
RESEARCH
SALES CAVE
OPERATIONS
HOUSEKEEPING
COMMUNICATIONS
6 rows selected.
SQL>
/
To convert this query into the ANSI SQL syntax we have to do this:
SQL> select d.dname
2 , e.ename
3 from dept d
4 left outer join emp e
5 on ( d.deptno = e.deptno
6 and e.ename = 'CAVE' )
7 /
DNAME ENAME
-------------- ----------
ACCOUNTING
RESEARCH
SALES CAVE
OPERATIONS
HOUSEKEEPING
COMMUNICATIONS
6 rows selected.
SQL>
Note that if we don't include the additonal clause in the JOIN but leave it in the WHERE clause we get a different result:
SQL> select d.dname
2 , e.ename
3 from dept d
4 left outer join emp e
5 on ( d.deptno = e.deptno )
6 where e.ename = 'CAVE'
7 /
DNAME ENAME
-------------- ----------
SALES CAVE
SQL>
This is the equivalent of omitting the (+) in the second old skool query.
The query is joining the 2 tables jobs, and address. These tables are joining on the field ip_num but you are looking for the records that exist in the jobs table but do not exist in the address table.
This is a LEFT OUTER JOIN. This query could also be written
SELECT j.ip_num
FROM jobs j
LEFT OUTER JOIN address a
ON j.ip_num=a.ip_num
WHERE j.jobtype='C' AND
a.sel_code(+)='H' AND
a.ip_num is null
ORDER BY a.ip_num
It might be useful to see a visual picture joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Oracle Hierarchical query: how to include top-level parent

I have a hierarchical query to track a reporting structure. This almost works, except that it's not reporting the very top level node, probably because the top-level people "report" to themselves.
The query is:
select
level,
empid,
parentid
from usertable
connect by nocycle prior parentid= empid
start with empid = 50
This produces:
LEVEL EMPID PARENTID
------ ----- --------
1 50 258
2 258 9555
3 9555 17839
I'm not getting a level 4, since it would look like:
4 17839 17839
Without changing data, is there a way to modify my query so that all 4 levels are returned? The goal is to get the empids, so I can do a check for
id in (hierarchical subquery)
BTW, if I remove the nocycle from the query I get an error.
Chris,
You only get 3 rows because your top level row is not set the way it should to handle hierarchical queries. Typically the top level row, or president KING in Oracle's well known EMP table, has no manager. In your case you should not set the parentid of 17389 to 17389 itself, but to NULL. Either update the table accordingly, or use a view to accomodate for this situation.
An example:
SQL> select empno
2 , mgr
3 from emp
4 where empno in (7876,7788,7566,7839)
5 /
EMPNO MGR
---------- ----------
7566 7839
7788 7566
7839 7839
7876 7788
4 rijen zijn geselecteerd.
This part of the EMP table has four levels with its top level row (7839) set to itself. The same as your empid 17839. And this leads to only three rows using your query:
SQL> select level
2 , empno
3 , mgr
4 from emp
5 connect by nocycle prior mgr = empno
6 start with empno = 7876
7 /
LEVEL EMPNO MGR
---------- ---------- ----------
1 7876 7788
2 7788 7566
3 7566 7839
3 rijen zijn geselecteerd.
Either use a (inline) view to set the mgr/parentid column to null for the top level:
SQL> select level
2 , empno
3 , mgr
4 from ( select empno
5 , nullif(mgr,empno) mgr
6 from emp
7 )
8 connect by nocycle prior mgr = empno
9 start with empno = 7876
10 /
LEVEL EMPNO MGR
---------- ---------- ----------
1 7876 7788
2 7788 7566
3 7566 7839
4 7839
4 rijen zijn geselecteerd.
Or fix your data with an UPDATE statement:
SQL> update emp
2 set mgr = null
3 where empno = 7839
4 /
1 rij is bijgewerkt.
SQL> select level
2 , empno
3 , mgr
4 from emp
5 connect by nocycle prior mgr = empno
6 start with empno = 7876
7 /
LEVEL EMPNO MGR
---------- ---------- ----------
1 7876 7788
2 7788 7566
3 7566 7839
4 7839
4 rijen zijn geselecteerd.
And you can leave out the NOCYCLE keyword as well, after you are done fixing.
Regards,
Rob.
You need to do the hierarchy the other way around, from the root to the leaves.
select
level,
empid,
parentid
from usertable
start with empid = 17839
connect by empid != 17839 and prior empid = parentid
LEVEL EMPID PARENTID
---------------------- ---------------------- ----------------------
1 17839 17839
2 9555 17839
3 258 9555
4 50 258
4 rows selected
You don't have to change your structure.
just use the following query
select
level,
empid,
parentid
from usertable
connect by prior parentid = empid
AND parentid <> empid -- This line prohibits cycling and ALLOWS a row where parentid = empid
start with empid = 50
Van Heddegem Roeland's answer doesn't work for me, I had already tried that, but I have managed to do it without an inline view, in the connect clause, by adding:-
and prior empid <> parentid
The following post explains why that works - if you can get your head round it! Although it does make sound logical sense once you do 'get it'. (It's to do with the order of evaluation of each side of the <> operator.)
Oracle: Connect By Loop in user data
The inline view will work but without research on your particular dataset, I don't know what impact an inline view might have on the query path. Adding the extra clause is probably the 'correct' way to do it in most situations, IMHO.
seems like you have a cycle in data. Without "nocycle" it will not work straight away. If you know that all your data has maximum nesting level 4, then you could add condition "and level <= 4" and remove nocycle. Should work.

Resources