Como resolver querys jerárquicas en SQL 2005 o 2008

by 18. abril 2009 15:10

En muchas oportunidades tenemos la necesidad de resolver este tipo de querys, por ejemplo para una tabla de empleados, de menús , una estructura de productos, etc..... Armar este tipo de querys jerárquicas no suelen ser algo simple para la mayoría de los desarrolladores. En este ejemplo que les muestro en el post hare una query jerárquica en SQL 2005 o 2008 utilizando unas nuevas sentencias TSQL llamada CTE (Common Table Expresion).

-- CREAMOS UNA TABLA EMPLEADOS

IF OBJECT_ID('DBO.EMPLEADOS') IS NOT NULL
   DROP TABLE DBO.EMPLEADOS
GO

CREATE TABLE DBO.EMPLEADOS (ID INT NOT NULL,JEFE_ID INT NULL,
                            NOMBRE VARCHAR(300),Puesto varchar(300))
GO

INSERT INTO DBO.EMPLEADOS VALUES (100,NULL,'Martin','CEO')
INSERT INTO DBO.EMPLEADOS VALUES (101,100,'Maxi','Gerente Sistemas')
INSERT INTO DBO.EMPLEADOS VALUES (102,100,'Veronica','Gerente Calidad')
INSERT INTO DBO.EMPLEADOS VALUES (103,101,'Javier','Analista SR')
INSERT INTO DBO.EMPLEADOS VALUES (104,101,'Gabriel','DBA')
INSERT INTO DBO.EMPLEADOS VALUES (105,102,'Ana','Auditora')
INSERT INTO DBO.EMPLEADOS VALUES (106,103,'Luis','Programador')
INSERT INTO DBO.EMPLEADOS VALUES (107,105,'Jose','Asistente')
GO

-- MOSTRAMOS EL ORGANIGRAMA HASTA EL NIVEL 2

WITH REPORTE(JEFE_ID, ID,NOMBRE,PUESTO,NIVEL) AS 
(
    SELECT JEFE_ID, ID,NOMBRE,PUESTO, 0 AS NIVEL
    FROM DBO.EMPLEADOS
    WHERE JEFE_ID IS NULL -- TRAEMOS TODOS LOS QUE NO TIENEN JEFES 
    UNION ALL
    SELECT e.JEFE_ID, e.ID, E.NOMBRE,E.PUESTO,NIVEL + 1
    FROM DBO.EMPLEADOS e
        INNER JOIN REPORTE d
        ON e.JEFE_ID = d.ID 
)
SELECT REPORTE.JEFE_ID, REPORTE.ID, REPORTE.NOMBRE,REPORTE.PUESTO,
EMPLEADOS.NOMBRE AS JEFE_NOMBRE, EMPLEADOS.PUESTO AS PUESTO_JEFE 
FROM REPORTE LEFT JOIN DBO.EMPLEADOS ON
REPORTE.JEFE_ID = EMPLEADOS.ID
WHERE NIVEL <= 2 
GO

 

En SQL Server 2008 disponemos además de esto la posibilidad de utilizar un tipo de dato jerárquico llamado Hierarchyid

Tags:

TSQL | How To | SQL 2005 | SQL 2008

Comentarios

22/07/2009 0:31:25 #

Hey I love your style I will subscribe for your feed please keep posting!

Maurice Lacroix United States

13/08/2009 23:48:32 #

I don't like your template but your posts are quite good so I will check back!

Tommy Bahama Mens Steel United States

14/08/2009 22:18:20 #

Tried to autotranslate you site not understand the writing any hope deutsch version?

Pulsar Watch Pulsar Pf3481 United States

15/08/2009 21:29:21 #

Hmm strange this post is totaly irrelevant to the search query I entered in google but it was listed on the first page.

Womens Kenneth Cole Chic United States

16/08/2009 20:22:59 #

Do you earn decent money from this blog or are you doing it just for fun?

Iwc Portofino Mens Watch United States

17/08/2009 19:49:45 #

Do you accept guest posts? I would love to write couple articles here.

Triumph Motorcycles Mens Analog United States

18/08/2009 17:42:59 #

I don't like your template but your posts are quite good so I will check back!

Invicta Reserve Akula Mens United States

26/08/2009 9:26:12 #

Tried to autotranslate you site not understand the writing any hope deutsch version?

Baume Mercier Classima United States

27/08/2009 7:19:45 #

Please let me know if you are interested to work as article writer for me? I can offer $10/article.

Baume Mercier Classima United States

23/09/2009 0:17:18 #

amazing stuff thanx Smile

payday loans United States

23/09/2009 14:53:49 #

Excelente post. sin embargo me gustaria que agregaras como se hace para consultar por ejemplo en el caso de que un empleado tenga un jefe y si este jefe tiene un jefe se mostrara la informacion del jefe inmediato y el   jefe superior

elj Spain

22/10/2009 13:53:44 #

Thanks for sharing such informative post. Badly needed this for our project. Looking forward for more post about SQL server 2005. And if it is possible I do hope you'd add server 2008 also. Thanks

chinesepod review United States

22/10/2009 14:48:08 #

This is great, haven't noticed this is for SQL server 2008 also. Thanks pal. I believe there's quite a difference between 2005 and 2008 server.

chinesepod review United States

22/10/2009 14:48:32 #

This is great, haven't noticed this is for SQL server 2008 also. Thanks pal. I believe there's quite a difference between 2005 and 2008 server.

learning mandarin online United States

Maximiliano Damian Accotto