• Sony Francis @EY (11/26/2012)


    I have table with 20k records. I want to delete 20k-1000 records from the table. i.e keep the top 1000 records and rest of them are need to be deleted. I dont knw the table structure. I have tried using cte and row_number () . But its failed(Should mention the column name in order by clause).

    Is any body to help me write a single query for it

    What is the top 1000? There is no concept of order in a table. Since there are only 20k rows to be deleted I doubt that batching will help a lot, unless the rows are really large.

    You could do this fairly easily with a cte.

    ;with MyData as

    (

    select ROW_NUMBER() over(order by SomeField) as RowNum, * from YourTable

    )

    delete MyData where RowNum > 1000

    If you need more specific help you are going to have to provide more specific information (ddl, sample data, desired output). See the first link in my signature for best practices when posting questions.

    I am horrified by your comment that you are deleting all but 1,000 rows out of a table and you don't even know the structure of the table. :w00t:

    It sounds like you have tried something but simply saying "it failed" does not provide any kind of information. What happened? Did you get an error message?

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/