How to use aggregate function MAX in c#?


If you want to put some criteria on columns and retrieve values from it, then you can use aggregate functions. Calculations , computation part is easy with aggregate functions. I hope it will be useful for you all.

How to use aggregate function MAX in c#?
Example:
In this example, ID is the column name in User table.
We will get records whose ID is maximum. Similarly you can use MIN , SUM and many other aggregate functions.
GetConnString() method is used to return the value of ConnectionString which is stored in web.config.


public string GetMaxUserID()
{
string ConnString = GetConnString();
string sqlString = "SELECT MAX(User.ID) FROM [User]";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlString, conn))
{
cmd.CommandType = CommandType.Text;
conn.Open();
if (cmd.ExecuteScalar() != null)
{
object obj = cmd.ExecuteScalar();
conn.Close();
conn.Dispose();
return obj.ToString();
}
else
{
conn.Close();
conn.Dispose();
return string.Empty;
}
}
}
}

public static string GetConnString()
{
return ConfigurationManager.AppSettings["ConnectionString"].ToString();
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: