简体   繁体   中英

update index after a delete operation

I have a Customer Table that has a CustIndex column. From the UI a User can delete a customer that was for example at Index 3. What I need to do then determine if there was a Customer with an Index at 4 and renumber it to be 3, (so basically keep the sequence).

At the minute I just have some code like below:

    private void UpdateCustomerIndexes(IList<CustomerDTO> customers)
    {
        var customerIndexes = customers.Select(c => new { c.customerId, c.customerIndex });

        //unitIndexes.Select(u => u.)
    }

I am keeping wanting to keep the CustomerId so if I need to update the DB I can say update customer set index = 3 where customerid = 4 for example.

So if I had 5 customer on the UI and I delete Customer at Index 5

If I set a breakpoint on customerIndexes, the data is:

{ CustomerId = 33, CustomerIndex = 1 },
{ CustomerId = 34, CustomerIndex = 2 },
{ CustomerId = 35, CustomerIndex = 3 },
{ CustomerId = 36, CustomerIndex = 4 }

So, in this case, the CustomerIndex is in sequence so there is nothing to do. However, lets say now I deleted CustomerIndex 2 on the UI. The data would now look like:

{ CustomerId = 33, CustomerIndex = 1 },
{ CustomerId = 35, CustomerIndex = 3 },
{ CustomerId = 36, CustomerIndex = 4 }

Now the Customer Index is out of sequence and I need to renumber CustomerIndex 3 to 2 and CustomerIndex 4 to 3 and then save this to the DB so I can say make the update statements setting the Index to the new value for that CustomerId.

I know my CustomerIndex will never go above 50 so would it be an idea to use something like:

var list = new List<int>(new[] { customerIndexes.Select(c => c.customerIndex) });
var result = Enumerable.Range(0, 50).Except(list);

However, I think this will only tell me if a number in sequence is missing - I am missing how to save which index needs to be updated for which customerid or do nothing in the case when they are in sequence

After you delete the record with CustomerIndex of 2, run the following SQL:

UPDATE TableName SET CustomerIndex = CustomerIndex - 1 WHERE CustomerIndex > 2

This will ensure the CustomerIndex of all 'greater' records are reduced by 1 to compensate.

Similarly, if a customer deletes CustomerIndex of 5, change both references to 2 above to 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM