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 2008 Forums
 Transact-SQL (2008)
 Recursive code to create a list

Author  Topic 

charya
Starting Member

1 Post

Posted - 2014-07-08 : 11:42:24
Hey guys

I wasnt really sure if the thread title was great, but here's the problem.

What I need?: A way of dynamically inserting a list in the WHERE clause of a query. (in the form, WHERE ID = 1,2,3,6,9 etc)

Imagine an example DB with 3 columns Student ID, Name, Teacher_ID. (Lets assume Teacher_ID with value 100 means its the Headmaster)

I need to create a list with Student ID's, who are directly/indirectly under the Headmaster. Example:

Headmaster
Teacher 1 (ID 200)
Teacher 2 (ID 250)
Student 1 (ID 300)
Director
Teacher 4
Student 5

In the above example, since I only want those students/teachers under the headmaster, either directly/indirectly, my list would contain Teacher 1, Teacher 2, and Student 1. (In my case, just their ID's, so 200, 250, 300)

Director, Teacher 4 and Teacher 5 wouldnt be in the list since theyre not directly/indirectly Headmaster.

Hope I explained that well.
If you have any questions let me know :)

Thanks!

namman
Constraint Violating Yak Guru

285 Posts

Posted - 2014-07-08 : 16:51:12
It is better to have table structure, sample data (with insert command) and list of expected output. Then explain why rows are selected or not selected.
Go to Top of Page
   

- Advertisement -