更新"订单"删除一行后的列?

时间:2014-05-08 11:07:29

标签: sql sql-server sql-server-2012

我有一个ProductsImages表,其中包含ImageId, Productid ,Order

ProductId   ImageId    Order
----------------------------
    1          1        1
    1          2        2
    1          3        3
    1          4        4
    1          5        5

当我删除一行时,请说ProductId = 1 ImageId = 1我需要更新订单栏:

ProductId   ImageId    Order
----------------------------
    1          2        1
    1          3        2
    1          4        3
    1          5        4

1 个答案:

答案 0 :(得分:1)

执行delete后,您可以进行更新:

with toupdate as (
      select pi.*,
             row_number() over (partition by productId order by [order]) as neworder
      from ProductImages pi
     )
update toupdate
    set [order] = neworder;

以上更新了整个表格。如果您只想更新已更改的产品,请添加where子句:

with toupdate as (
      select pi.*,
             row_number() over (partition by productId order by [order]) as neworder
      from ProductImages pi
      where pi.ProductID = @ProductId
     )
update toupdate
    set [order] = neworder;