Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

sql - MAX(id) using SqlDataReader C#

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) ?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...