1

Given an example table such as:

CREATE TABLE TESTING_Order(
    Order INT, 
    Name VARCHAR(5)
)

INSERT INTO TESTING_Order 
VALUES
    (0, 'Zero'),
    (1, 'One'),
    (2, 'Two'),
    (3, 'Three'),
    (4, 'Four'),
    (5, 'Five'),
    (6, 'Six'),
    (7, 'Seven')

I'd like to know how to implement a sort of 'Stack' to show, for instance, the turn order in a game where the first player moves 'left' each turn. I can accomplish this using two update statements:

UPDATE TESTING_Order
SET Order = Order + 1

UPDATE TESTING_Order 
SET Order = (SELECT Min(Order) -1 FROM TESTING_Order)
WHERE Order = (SELECT MAX(Order) FROM TESTING_Order)

I was wondering if there is a cleaner/more proper way of doing this, and especially if that other way can be done using a single UPDATE statement.

In other words, I think what I'm after is a better implementation of a LIFO Stack that performs a push on every pop--excuse me for possibly butchering any terminology.

2
  • Are you just looking for a modulus operator, like ... SET Order = (Order + 1) % (SELECT COUNT(*) FROM Table)? (or MAX() + 1 if you preferred that over COUNT() for some reason; either way, it appears to assume that the numbers are all consecutive with no gaps) Regardless, if you execute your multiple statements within a transaction, they'll effectively be executed as one atomic operation, if that's what you're worried about.
    – Wiseguy
    Commented Jan 28, 2013 at 22:55
  • The modulus operator would work perfectly. Either solution is acceptable--and you're right, the assumption is made that the values will be consecutive. I'm not as concerned about it executing once vs. executing twice, I was more curious about finding a way that could do it. Thanks so much for your feedback!
    – Jon
    Commented Jan 28, 2013 at 23:48

1 Answer 1

2

Just so that there is an answer here:

To cycle through the list I've decided to use:

UPDATE TESTING_Order
SET nOrder = 
    Case 
        WHEN (nOrder - 1) < 0 THEN (SELECT Count(*) FROM TESTING_Order) - 1
        WHEN (nOrder - 1) >= 0 THEN (nOrder - 1) % (SELECT MAX(nOrder) + 1 FROM TESTING_Order)
    END

This allows me to move the list in the correct way (which I realize my answer probably did not) and has the benefit of doing what I requested in just one statement. Thanks for pointing me in the right direction, Wiseguy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.