August 8, 2012 at 3:41 am
Is there any better way of implementing self joins in SQL Server.? I mean, instead of looping the same table many times, can we achieve it using some other method? Please help
August 8, 2012 at 4:31 am
A bit vague, can you clarify please?
Do you have an example?
-- Gianluca Sartori
August 8, 2012 at 4:48 am
This is the query... Can we achieve the same via some other method?
SELECT OS.NAME, OS.ITEMID, OS.PARENTID, OS2.NAME AS PARENTNAME, OS.HIERID, OS3.NAME AS HIERNAME,OS.HIERLEVEL,H.LEVELNAME
FROM OPERATIONALSTRUCTURE OS, OPERATIONALSTRUCTURE OS2, OPERATIONALSTRUCTURE OS3,HIERLEVELS H
WHERE OS.PARENTID = OS2.ITEMID AND OS.HIERID = OS3.ITEMID AND H.HIERID=OS3.HIERID AND H.HIERLEVEL=OS.HIERLEVEL
ORDER BY OS.HIERID, OS.PARENTID, OS.NAME
August 8, 2012 at 4:58 am
You can achieve the same thing with subqueries. If you're after better performance, I'm not sure that rewriting the query this way will improve things.
Also, consider that the semantics changed slightly, as now you're doing OUTER joins instead of INNER joins. Make sure this is ok in your case.
SELECT OS.NAME
,OS.ITEMID
,OS.PARENTID
,PARENTNAME = (
SELECT NAME
FROM OPERATIONALSTRUCTURE AS OS2
WHERE OS.PARENTID = OS2.ITEMID
)
,OS.HIERID
,HIERNAME = (
SELECT NAME
FROM OPERATIONALSTRUCTURE AS OS3
WHERE OS.HIERID = OS3.ITEMID
AND H.HIERID = OS3.HIERID
)
,OS.HIERLEVEL
,H.LEVELNAME
FROM OPERATIONALSTRUCTURE AS OS
INNER JOIN HIERLEVELS H
ON H.HIERLEVEL = OS.HIERLEVEL
ORDER BY OS.HIERID
,OS.PARENTID
,OS.NAME
Another possibility is CROSS APPLY:
SELECT OS.NAME
,OS.ITEMID
,OS.PARENTID
,PARENTNAME
,OS.HIERID
,HIERNAME
,OS.HIERLEVEL
,H.LEVELNAME
FROM OPERATIONALSTRUCTURE AS OS
INNER JOIN HIERLEVELS H
ON H.HIERLEVEL = OS.HIERLEVEL
CROSS APPLY (
SELECT NAME AS PARENTNAME
FROM OPERATIONALSTRUCTURE AS OS2
WHERE OS.PARENTID = OS2.ITEMID
) AS OS2
CROSS APPLY (
SELECT NAME AS HIERNAME
FROM OPERATIONALSTRUCTURE AS OS3
WHERE OS.HIERID = OS3.ITEMID
AND H.HIERID = OS3.HIERID
) AS OS3
ORDER BY OS.HIERID
,OS.PARENTID
,OS.NAME
Long story short, you always need to go back to the same table reading the information you need. I'm afraid there's no way around it.
Hope this helps
Gianluca
-- Gianluca Sartori
August 8, 2012 at 5:17 am
Thanks Sartori for your efforts.....
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply