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

前端 未结 7 1043
小鲜肉
小鲜肉 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 03:08

    I agree with the Hamed elahi and Glorfindel.

    My suggestion to add is you can delete and update using aliases

    /* 
      given a table bi_customer_actions
      with a field bca_delete_flag of tinyint or bit
        and a field bca_add_date of datetime
    
      note: the *if 1=1* structure allows me to fold them and turn them on and off
     */
    declare
            @Nrows int = 1000
    
    if 1=1 /* testing the inner select */
    begin
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    end
    
    if 1=1 /* delete or update or select */
    begin
      --select bca.*
      --update bca  set bca_delete_flag = 0
      delete bca
        from (
          select top (@Nrows) * 
            from bi_customer_actions
            where bca_delete_flag = 1
            order by bca_add_date
        ) as bca
    end 
    

提交回复
热议问题