2012-01-01 76 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"; 

然后原始代码行将起作用。

相关问题