Well I wouldn’t do that
I would have two statements
-- Student Statement SELECT S.StudentID, S.StudentName FROM Student S WHERE EXISTS ( SELECT * FROM StudentExam SE WHERE SE.StudentID = S.Student.ID); -- Exam Statement SELECT SE.StudentID, E.ExamID, E.ExamName, SE.Mark FROM StudentExam SE JOIN Exam E ON E.ExamID = SE.ExamID;
Then I will have a function that does this,
private IEnumerable<Tuple<int, ExamMark>> GetMarks() { ... setup the exam command here var reader = examCommand.ExecuteReader(); while (reader.Read()) { yield return Tuple.Create( reader.GetInt32(0), new ExamMark { reader.GetInt32(1), reader.GetString(2), reader.GetInt32(3) }); } }
Then I would have this function to call,
private IEnumerable<Student> GetStudents() { var resultLookup = GetMarks().ToLookup(t => t.Item1, t => t.Item2); ... setup the student command here var reader = studentCommand.ExecuteReader(); while (reader.Read()) { var studentId = reader.GetInt32(0); yield return new Student { studentId, reader.GetString(1), resultLookup[studentId].ToList() }); } }
If you want, you can do it all in one stored procedure and return multiple result sets.
Jodrell
source share