Display Last Record

  • How can display only the last record in an sql 2000 database table?

    Thanks

  • Do you have an identity column?

    Do you have a date inserted column?

    Select top 1 Col1, Col2 from dbo.YourTable order by IdentityCol desc

    or

    Select top 1 Col1, Col2 from dbo.YourTable order by DateInserted desc

    Otherwise you need a log reader to get that information.

  • Logically,without an ORDER BY clause, SQL Server is free to return the rows in any order, so any value of [col1] is correct. Recall that logically tables are unordered sets of data, so there is no first or last value in a table.

    If you are very specific to do that any way,

    Declare @column1 varchar(20)
    Declare @column2 varchar(20)
    SELECT @column1 = column1, @column2 = column2

    from table_name

     
    SELECT @column1, @column2
     
    Thanks,
    Ganesh

     

  • There is no such thing in the general sense since SQL Server does not have record numbers. You need a field such as an identity column or datetime stamp for when created or last updated. Then you can SELECT TOP 1 FROM ORDER BY DESC

  • Thanks, it works fine.

  • Remi,

    Apologies. I just noted that I effectively repeated your answer. I must have been asleep not to notice! No plagiarism intended.

  • No offense taken... not the first time it happens on this site .

  • Just so we cover all the options... try this:

    create table #a (uid int identity not null,

          EntryDate datetime not null default getdate(),

          UsrName varchar(30) not null ) on 'Primary'

    INSERT INTO #a

    (UsrName)

    VALUES ('Bill')

    INSERT INTO #a

    (UsrName)

    VALUES ('Mary')

    INSERT INTO #a

    (UsrName)

    VALUES ('Thomas')

    INSERT INTO #a

    (UsrName)

    VALUES ('Harry')

    select * from #a

    select * from #a

    where uid = (SELECT MAX(UID) FROM #a)

    hth... Mark Gelatt

  • Thanks, that works fine also.

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply