Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,

How to Select the last value from the sql database.

i have a table with customerId is a Primary key and i want last value show in a textbox.
and next generated primary key(Which is the use in current form) show in other textbox.
Posted
Comments
Thomas ktg 4-Sep-13 3:05am    
What do you mean by last value? Is that the last record inserted in the database table or something else?
Manish Arya 4-Sep-13 3:10am    
yes last record
means:
customer ID automatic generated like
CustomerId 1
CustomerId 2
CustomerId 3
CustomerId 4
CustomerId 5

now textbox1 =5 and then textbox2=6(which is currently used by the program)

Don't. Don't even think about it.
You cannot show "the next generated primary key" because in a multi-user system (and that is the only reason to use SQL) you do not know what the "next" value will be: it depends on what everybody else is doing, and the order in which they do it. Think about it: if you have two users both entering data, then they both will see the "next" value - and it will be the same value. But when they try to submit the data, they can't both use the same primary key without SQL correctly throwing an error. You only ever show a new value after it is used, or allocated at the very least (and then you have the fun of deallocation if they don't complete the operation for whatever reason).

The "last value" is also difficult to show, unless there is some order to the keys, or some field which records the date and time at which it was allocated. Then, all you have to do is
SQL
SELECT TOP 1 customerID FROM MyTable ORDER BY ... DESC
And fill in your sort criteria. If you do not specify an ORDER clause, then SQL is at liberty to return rows in any order it sees fit - it may return the last entered, but it doesn't have to: it can happily return rows in a different order every time you run the same query, if that is more efficient for it.
 
Share this answer
 
You can have Identity column and get the record based on that column.
C#
SELECT TOP 1 Id FROM table ORDER BY Id DESC

SQL SERVER – @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT – Retrieve Last Inserted Identity of Record[^]
 
Share this answer
 
you can use this

SQL
Select isnull(max(customerID),0) from mytable
 
Share this answer
 
Comments
[no name] 4-Sep-13 3:23am    
+5....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900