How do I get latest(max) date from the field?

I need to getLatestDate from certain field with some records.
Using C#, How do I compare all those dates in the records?
Let's say I have this table:

Test1: 5/20/2010
Test2: 8/12/2010
Test3: 2/1/2011
Test4: 11/2/2010

I want the code to return 2/1/2011 from Test3

Thanks,

Danny
luisr69Asked:
Who is Participating?
 
wdosanjosCommented:
You can try something like this.  The following sample connects to a local SQL Server Express instance (line with "new SqlConnection").

using System;
using System.Data;
using System.Data.SqlClient;

void Main()
{
	using (var cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True;MultipleActiveResultSets=True"))
	{
		cn.Open();
		
		try
		{
			var cmd = new SqlCommand();
			
			cmd.CommandText = "select max(YourDateColumn) as maxdate from YourTable";
			cmd.CommandType = CommandType.Text;
			
			cmd.Connection = cn;
			
			var maxdate = cmd.ExecuteScalar();
			
			Console.WriteLine(maxdate);
		}
		finally
		{
			cn.Close();
		}
	}
}

Open in new window

0
 
Bob LearnedCommented:
Are you talking about a database field, or a class field?  What version of .NET are you using?  Do you have any knowledge about LINQ?
0
 
wdosanjosCommented:
Where are the dates stored?
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
luisr69Author Commented:
Hi,

It's a database field, .NET 3.5
I'm using SQL Statement with Store Procedure.
Thanks, sorry I'm new with ASP.NET, please bear with me.
0
 
wdosanjosCommented:
You can get the correct value from a SQL statement like this:

select max(YourDateColumn) from YourTable

I hope this helps.
0
 
Bob LearnedCommented:
If you have a fixed number of fields, then you might be able to use a CASE statement in the query, but MAX only returns the maximum for a single column, not the max between different fields in the same row.
0
 
luisr69Author Commented:
SELECT MAX works as an SQL statement. Thanks,
How do I start with the C# Code?
And yes, it's a single column only for now.
Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.