2013-02-05 258 views
0

我有以下方法運行大約20個SQL查詢。將結果返回給客戶端的最佳方式是什麼?返回多個sql查詢結果 - C#

public int Results() 
{ 
    using (var conn = GetConnection()) 
      using (var cmd = new SqlCommand()) 
      { 
       cmd.Connection = conn; 
       cmd.CommandType = CommandType.Text; 
       cmd.CommandText = @"SELECT TOP 1 stdent_number from Students"; 

       conn.Open(); 
       var result = (int)cmd.ExecuteScalar(); 

       cmd.CommandText = @"SELECT TOP 1 class_number from Classes"; 
     var number = (int)cmd.ExecuteScalar(); 

       cmd.CommandText = @"SELECT TOP 1 table from Tables"; 
     var table = (int)cmd.ExecuteScalar(); 

       cmd.CommandText = @"SELECT TOP 1 suite from Suites"; 
     var suite = (int)cmd.ExecuteScalar(); 

       ..... 
       //I want to return result, number, table and suite so they can be populated on client 
     //What is the best way to return? Should I create IEnumerable and add values to it and return 
     //as IEnumerable or should these be returned all separately or as a dictionary? 
     //Also this is just an example in real time I have at least 15 values from sql queries that I  //want to return 

      } 
} 

回答

0

如果你不希望創建一個進程,然後嘗試像下面

通過所有的在像下面的字符串變量查詢...

string sql = "SELECT TOP 1 stdent_number from Students; SELECT TOP 1 class_number from Classes; SELECT TOP 1 table from Tables; SELECT TOP 1 suite from Suites"; 

之後嘗試像下面..

using (SqlConnection conn = new SqlConnection(connection)) 
{ 
    var result,number,table; 
    conn.Open(); 
      Cmd = new SqlCommand(sql, conn); 
      SqlDataReader sqlReader = Cmd.ExecuteReader(); 
      while (sqlReader.Read()) 
      { 
       result = dr[0].ToString(); 
      } 

      sqlReader.NextResult(); 

      while (sqlReader.Read()) 
      { 
       number = dr[0].ToString(); 
      } 

      sqlReader.NextResult(); 

      while (sqlReader.Read()) 
      { 
       table = dr[0].ToString(); 
      } 

      sqlReader.Close(); 
      Cmd.Dispose(); 
      conn.Close(); 
} 

也可以嘗試此鏈接:Return multiple set

+0

Pandian - 其實我們不是找誰g創建一個存儲過程。有沒有其他更好的方法來做到這一點? – NoviceMe

+0

@NoviceMe: - 我已經更新了我的代碼與出proc ...試試這.. – Pandian

0

如果我理解你的問題正確,你需要如何將所有的成功查詢數據從該函數傳回客戶端。 我建議您創建自己的類(DTO的[數據傳輸對象]),以將多個信息從您的函數傳遞給客戶端。而不是使用返回Int類型的函數。