Sql server SQL datareader字段名称超出范围

Sql server SQL datareader字段名称超出范围,sql-server,Sql Server,我有个问题需要帮助。我有以下疑问: SqlCommand randCode = new SqlCommand("(SELECT COUNT(student_ID) FROM COMPLETED)", conn); SqlDataReader randCodeR; connectie.Open(); randCodeR = randCode.ExecuteReader(); int count = randCodeR

我有个问题需要帮助。我有以下疑问:

        SqlCommand randCode = new SqlCommand("(SELECT COUNT(student_ID) FROM COMPLETED)", conn);
        SqlDataReader randCodeR;
        connectie.Open();
        randCodeR = randCode.ExecuteReader();

        int count = randCodeR.GetOrdinal("student_ID");
有500名学生已完成,randCodeR有一个值为500的字段。现在,我想将该值输入count变量,但当我尝试上面的代码时,它表示randCodeR.GetOrdinal(“student_ID”)中的student_ID超出范围。为什么它在datareader中看不到student_ID?如何从中获取值?谢谢


Microsft SQL server 2012

,因为
学生ID
不存在。在计算列上指定别名将删除错误

string _sqlQuery = "SELECT COUNT(student_ID) student_ID FROM COMPLETED";
SqlCommand randCode = new SqlCommand(_sqlQuery, conn);
改变

int count = randCodeR.GetOrdinal("student_ID");


因此,不要使用返回结果集中列的索引中的
SqldataReader.GetOrdinal
。您根本不需要读卡器。

嘿,我得到以下错误:“System.Data.SqlClient.SqlDataReader”不包含“ExecuteScalar”的定义,并且找不到接受“System.Data.SqlClient.SqlDataReader”类型的第一个参数的扩展方法“ExecuteScalar”(您缺少using指令或程序集引用吗?) ? 我已经使用System.Data.SqlClient;包括在内。@NiekJonkman:我的错,编辑了我的答案。你必须使用
SqlCommand.ExecuteScalar
@NiekJonkman:记住接受最好的答案。很乐意帮忙。
int count = (int)randCode.ExecuteScalar();