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.
| Author |
Topic |
|
dewacorp.alliances
452 Posts |
Posted - 2009-05-26 : 22:44:22
|
| Hi thereI have a table OrganisationStructure like this:OrganisationID INTParentOrganisationID INTOrganisationName VARCHAR(64)1 | 0 | Company2 | 1 | IT DIVISION 3 | 2 | IT SYSTEM BUSINESS UNIT4 | 1 | MARKETING DIVISION5 | 4 | DONATION BUSINESS UNITI 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. |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-05-27 : 10:05:12
|
quote: Originally posted by dewacorp.alliances Hi thereI have a table OrganisationStructure like this:OrganisationID INTParentOrganisationID INTOrganisationName VARCHAR(64)1 | 0 | Company2 | 1 | IT DIVISION 3 | 2 | IT SYSTEM BUSINESS UNIT4 | 1 | MARKETING DIVISION5 | 4 | DONATION BUSINESS UNITI 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=@IDUNION ALLSELECT os.OrganisationID ,os.ParentOrganisationID, os.OrganisationName FROM Org_CTE cJOIN OrganisationStructure osON os.ParentOrganisationID=c.OrgID)SELECT *FROM Org_CTE |
 |
|
|
|
|
|
|
|