Question

I have a ProductsImages table which includes ImageId, Productid ,Order :

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

When I delete a row, let's say ProductId = 1 ImageId = 1 I need to update the order column :

ProductId   ImageId    Order
----------------------------
    1          2        1
    1          3        2
    1          4        3
    1          5        4
Was it helpful?

Solution

After you do the delete, you can do an update:

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

The above updates the whole table. If you just want to update the changed product, add a where clause:

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top