2012-01-01 50 views
1

我正在開發一個Web應用程序,通過電子郵件向所有用戶發送測驗。如果數據庫中有多個測驗未發送給用戶,系統應該選擇最小測驗ID而不是最大測驗ID。爲什麼我在SQL查詢中使用MIN時系統中出現錯誤?

string quizid = ""; 

// Open DB connection. 
conn.Open(); 

string cmdText = "SELECT MIN (QuizID) FROM dbo.QUIZ WHERE IsSent <> 1"; 
using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 
{ 
    SqlDataReader reader = cmd.ExecuteReader(); 
    if (reader != null) 
    { 
     while (reader.Read()) 
     { 
      // There is only 1 column, 
      // so just retrieve it using the ordinal position 
      quizid = reader["QuizID"].ToString(); 
     } 
     } 
     reader.Close(); 
    } 

當我用MIN,它給了我下面的錯誤:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: QuizID

Source Error:

> Line 69:      { 
> Line 70:       // 
> There is only 1 column, so just retrieve it using the ordinal position 
> Line 71:       quizid = reader["QuizID"].ToString(); 
> Line 72: 
> Line 73:      } 
+0

'reader'永遠不會爲空。 – SLaks 2012-01-01 12:46:19

回答

1

或者,(與正確答案一起) 您可以命名該列,你想

string cmdText = "SELECT MIN (QuizID) AS mQuizID FROM dbo.QUIZ WHERE IsSent <> 1"; 
quizid = reader["mQuizID"].ToString(); 
4

MIN(QuizID)是一個未命名的計算列。

您可以編寫reader[0]來選擇第一列,或者通過編寫SELECT MIN(QuizID) AS SomeName FROM ...來命名該列。

2

只是做的錯誤線以上的評論說:

quizid = reader[0].ToString(); 

或者,如果你想使用的名稱,則必須在SQL語句中給別名:

string cmdText = "SELECT MIN (QuizID) As QuizID FROM dbo.QUIZ WHERE IsSent <> 1"; 

然後原始代碼行將起作用。

相關問題