Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Last Record

Author  Topic 

Manoj Kayastha
Starting Member

3 Posts

Posted - 2002-04-04 : 06:18:49
Dear friends!

Me from Nepal. I think, there must be a builtin function or other way, to find out the last record of a table. Pleas help me.

Thanks
manoj

dsdeming

479 Posts

Posted - 2002-04-04 : 07:43:40
In a SQL database, first and last rows are meaningless unless you have an identity column. Then you could select where id = MAX( id ) to get the last row or where id = @@identity to get the row you just inserted.

Go to Top of Page

LarsG
Constraint Violating Yak Guru

284 Posts

Posted - 2002-04-04 : 07:45:15
The idea of last (or first) row in a table in a relational database is a misconception. Rows are only identified by the values in the columns in the table. You can get the row(s) which has the largest (or smallest) value in some column. To get the highest value in a column you can do

select max(aleb) from ogrish

if you wish to have all columns for row(s) that have this maximum value you can use the following query


select * from ogrish where aleb in (select max(aleb) from ogrish)


The above query uses standard sql and will function in most DBMS's
A shorter formulation that only works in sql server and Access is

select top 1 * from ogrish order by aleb desc

Go to Top of Page

joldham
Wiseass Yak Posting Master

300 Posts

Posted - 2002-04-04 : 07:45:49
If you have an identity seed column, then you could find perform
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM table)

If you can post your table design, then we might have additional or better ideas.

Jeremy

Go to Top of Page

Nazim
A custom title

1408 Posts

Posted - 2002-04-04 : 07:46:00
Hi Manoj,

How will you determine the last record??. is it the last record inserted? or the last record updated ?.

therez no way sql server can find out this information. you need to have a seperate audit table or to store the information or a column basing on which you know the last record .most probably a datetime column will work for both updated and inserted records. a identity field may work well for inserted too(ofcourse if the user doesnt chose to insert the record explicity putting his/her own value in this column).

if therez such a field then
select * from tablename t inner join
(select max(columnname) M from tablename) k
on t.columname=k.m

But i repeat AFAIK therez no automatic or inbuilt way from which it can be determined the order of inserts or updates from Sql Server.

HTH

SNIPED SNIPED SNIPED
--------------------------------------------------------------


Edited by - Nazim on 04/04/2002 07:47:48
Go to Top of Page
   

- Advertisement -