How to delete the top 1000 rows from a table using Sql Server 2008?

前端 未结 7 1044
小鲜肉
小鲜肉 2020-12-01 02:34

I have a table in SQL Server. I would like to delete the top 1000 rows from it. However, I tried this, but I instead of just deleting the top 1000 rows it deleted all the

7条回答
  •  一个人的身影
    2020-12-01 02:50

    May be better for sql2005+ to use:

    DELETE TOP (1000)
    FROM [MyTab]
    WHERE YourConditions
    

    For Sql2000:

    DELETE FROM [MyTab]
    WHERE YourIdField IN 
    (
      SELECT TOP 1000 
        YourIdField 
      FROM [MyTab]
      WHERE YourConditions
    )
    

    BUT

    If you want to delete specific subset of rows instead of arbitrary subset, you should explicitly specify order to subquery:

    DELETE FROM [MyTab]
    WHERE YourIdField IN 
    (
      SELECT TOP 1000 
        YourIdField 
      FROM [MyTab]
      WHERE YourConditions
      ORDER BY ExplicitSortOrder
    )
    

    Thanks tp @gbn for mentioning and demanding the more clear and exact answer.

提交回复
热议问题