Reputation: 455
For example, I have table with a column ID
as seen below:
ID
------
1
2
3
4
How can I query so I can get 4?
I'm using SQL Server 2012
Upvotes: 1
Views: 5141
Reputation: 412
You can also use
SELECT TOP 1 ID
FROM mytable
ORDER BY ID DESC
to forego calculation and utilize a sort feature to find the highest value in whatever column you're checking.
Thanks,
C§
Upvotes: 2
Reputation: 8656
You should use SELECT max(Id) FROM mytable
And you should be able to accomplish that using code like this:
int maxId = -1;
string connectionString = "yourConnectionString";
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT max(Id) FROM mytable", con))
{
maxId = Convert.ToInt32(command.ExecuteScalar());
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Upvotes: 2