Software & Finance





ADO.NET - How to get result from two table in sqlDataReader?





ADO.NET - How to get result from two table in sqlDataReader?

 

Sample query is given below:

    
public void ReadStudentData(string myConnString) {

    string mySelectQuery = "SELECT student.name, student.age, student.cty, course.name FROM student INNER JOIN course on student.studentrollno = course.studentrollno";

    SqlConnection myConnection = new SqlConnection(myConnString);
    SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);
    myConnection.Open();

    SqlDataReader myReader;
    myReader = myCommand.ExecuteReader();

    while (myReader.Read()) {
       Console.WriteLine("Name: " + myReader.GetString(0) );
       Console.WriteLine("Age: " +  myReader.GetInt32(1) );
       // Access other fields
    }
    
    myReader.Close();    
    myConnection.Close();
 }