Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Loop through without Cursor

Author  Topic 

dewacorp.alliances

452 Posts

Posted - 2009-05-26 : 22:44:22
Hi there

I have a table OrganisationStructure like this:

OrganisationID INT
ParentOrganisationID INT
OrganisationName VARCHAR(64)

1 | 0 | Company
2 | 1 | IT DIVISION
3 | 2 | IT SYSTEM BUSINESS UNIT
4 | 1 | MARKETING DIVISION
5 | 4 | DONATION BUSINESS UNIT

I want to have a query that if the app passing let say OrganisatinID = 1 means that it will loop (looking at parent/child) through till end of this table and grap all possible Returned OrganisatioIDs = (1, 2, 3, 4, 5).

Other if passing OrganisationID = 2 then Returned Organisation IDs = (2, 3)

Other if passing OrganisationID = 3 then Returned Organisation ID = 3

Any ideas to do this without cursor?

LoztInSpace
Aged Yak Warrior

940 Posts

Posted - 2009-05-27 : 03:55:00
Check out CTE (using the WITH clause). You'll find heaps of examples here & google.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-05-27 : 04:52:24
See http://www.sqlteam.com/FORUMS/topic.asp?TOPIC_ID=89335


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-05-27 : 10:05:12
quote:
Originally posted by dewacorp.alliances

Hi there

I have a table OrganisationStructure like this:

OrganisationID INT
ParentOrganisationID INT
OrganisationName VARCHAR(64)

1 | 0 | Company
2 | 1 | IT DIVISION
3 | 2 | IT SYSTEM BUSINESS UNIT
4 | 1 | MARKETING DIVISION
5 | 4 | DONATION BUSINESS UNIT

I want to have a query that if the app passing let say OrganisatinID = 1 means that it will loop (looking at parent/child) through till end of this table and grap all possible Returned OrganisatioIDs = (1, 2, 3, 4, 5).

Other if passing OrganisationID = 2 then Returned Organisation IDs = (2, 3)

Other if passing OrganisationID = 3 then Returned Organisation ID = 3

Any ideas to do this without cursor?





;With Org_CTE (OrgID,POrgID,OrgName) AS
(SELECT OrganisationID ,ParentOrganisationID, OrganisationName
FROM OrganisationStructure
WHERE OrganisationID=@ID
UNION ALL
SELECT os.OrganisationID ,os.ParentOrganisationID, os.OrganisationName
FROM Org_CTE c
JOIN OrganisationStructure os
ON os.ParentOrganisationID=c.OrgID
)

SELECT *
FROM Org_CTE
Go to Top of Page
   

- Advertisement -