MAX(id) 使用 SqlDataReader C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9245197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:31:39  来源:igfitidea点击:

MAX(id) using SqlDataReader C#

c#sqlsqldatareader

提问by Dan Kanze

How do I change this:

我如何改变这个:

        using (SqlCommand myCommand = myConnection.CreateCommand())
        {
            myConnection.Open();
            myCommand.CommandText = "SELECT FormID FROM tbl_Form";
            using (SqlDataReader reader = myCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    int FormID = reader.GetInt32(reader.GetOrdinal("FormID"));
                    MessageBox.Show(FormID.ToString());
                }
            }
        }

to get MAX(FormID)?

获得MAX(FormID)

My natural tendency is to throw a MAX around FormID but I'm getting an IndexOutOfRange exception.

我的自然倾向是在 FormID 周围抛出 MAX,但我收到 IndexOutOfRange 异常。

采纳答案by BrokenGlass

When you select the maximum id you shouldn't use a SqlDataReader- the query returns just one item, which by default is unnamed so your existing query breaks because it expects a result named "FormID" - although you could have "fixed" your query by using "SELECT MAX(FormID) as FormId FROM tbl_Form". Instead use ExecuteScalar():

当您选择最大 id 时,您不应使用 a SqlDataReader- 查询仅返回一项,默认情况下未命名,因此您现有的查询会中断,因为它需要名为“FormID”的结果 - 尽管您可以“修复”您的查询使用"SELECT MAX(FormID) as FormId FROM tbl_Form". 而是使用ExecuteScalar()

myCommand.CommandText = "SELECT MAX(FormID) FROM tbl_Form";
int maxId = Convert.ToInt32(myCommand.ExecuteScalar());

回答by Antony Scott

It's been a while since I used this style of database access, but I think you just need

我已经有一段时间没有使用这种数据库访问方式了,但我认为您只需要

select max(FormID) from tbl_Form

along with a call to ExecuteScalar

以及对 ExecuteScalar 的调用