Results 1 to 7 of 7

Thread: selecting last 100 rows from a table.

  1. #1
    Join Date
    Jul 2003
    Posts
    7

    selecting last 100 rows from a table.

    I have a temporary table that contain 1000 rows. I want to insert records from 900 to 1000 into another temporary table. Is ther any query that will do this in SQL server. With cursors I can do that but I need one shot query. Please give me some suggestions.

    I using this query but it is not returning any rows.
    select * into #t2 from #t1 t1 where not exists( select top 900 * from #t1 t2)

  2. #2
    Join Date
    Mar 2003
    Location
    NJ
    Posts
    201
    Do you have a column for identity?
    If you does.

    Then do the insert as

    insert into TempTable select top 100 * from TableName order by ID_Col desc

  3. #3
    Join Date
    Jul 2003
    Posts
    7
    I don't have one.

  4. #4
    Join Date
    Mar 2003
    Location
    NJ
    Posts
    201
    so what is the criteria for you the pick last 100 rows?

  5. #5
    Join Date
    Jul 2003
    Posts
    7
    Order by can be any thing from original table before inserting into Temp table1. Temp table1 has no criteria. Just pick last 100 rows.

  6. #6
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932
    Is there any unique key in the table?.

    If not then you may have to use one more layer of temp table

    select identity(int,1,1) as id, *
    into #t3
    from #t1

    select a.c1,...a.cn
    into #t2
    from #t3 as a
    where a.id < 101

  7. #7
    Join Date
    Jan 2004
    Posts
    14
    if you just want to use only one temporary table then what you could do is:

    --------
    insert into #t2
    select top 100 * from #t1
    order by id desc
    ---------

    Here id can be any columns that you want to sort with.

    I hope this helps.

    Niben
    Last edited by niben; 01-12-2004 at 05:05 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •