Combine two different unrelated SQL queries( returning single column results) into one query result with two columns

后端 未结 3 1465
栀梦
栀梦 2021-01-29 03:37

I have two sql queries. In first I am returing total marks obtained and in other i am returning maximum marks . Now i want to combine both in single query for the purpose of ma

3条回答
  •  梦如初夏
    2021-01-29 03:56

    Even with accepted answer it is make sense to mention that probably the right thing to do is to use separate queries, as they are and just use MARS on the client, in case performance was an issue.

    UPDATE: Thats how you can combine several queries and read them all together:

    using(var conn = SqlConnection(...)) {
       conn.Open();
       var cmd = conn.CreateCommand()
       cmd.CommandText = 
        @"Select SUM(MarksObtained) as MarksObtained 
          from tbAnswers 
          where QID IN(Select QID from tbQuestions where ExamID =2);"
      + @"Select SUM(Marks) as MaxMarks 
          from tbQuestions 
          where ExamID =2";
    
       using (var dr = cmd.ExecuteReader) {
            ... // read MarksObtained
            dr.NextResult()
            ... // readMaxMarks
            dr.Close()
       }
       conn.Close()
    }
    

    MSDN IDataReader.NextResult

提交回复
热议问题