使用SqlDataReader的C#MAX(ID) [英] MAX(id) using SqlDataReader C#

查看:138
本文介绍了使用SqlDataReader的C#MAX(ID)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要如何改变这样的:

        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());
                }
            }
        }



获得 MAX (FormID)

我的自然倾向是抛出一个MAX各地FormID但我得到一个IndexOutOfRange例外。

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

推荐答案

当您选择最大的id,你不应该使用 SqlDataReader的 - 查询返回只有一个项目,默认情况下是无名所以现有查询休息,因为它需要一个名为FormID的结果 - 尽管你可能会使用固定查询选择MAX(FormID)作为FormId FROM tbl_Form。而是使用 的ExecuteScalar()

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():

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

这篇关于使用SqlDataReader的C#MAX(ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆