Swap unique indexed column values in database

前端 未结 12 961
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 06:36

I have a database table and one of the fields (not the primary key) is having a unique index on it. Now I want to swap values under this column for two rows. How could this

12条回答
  •  情深已故
    2020-12-03 06:56

    Assuming you know the PK of the two rows you want to update... This works in SQL Server, can't speak for other products. SQL is (supposed to be) atomic at the statement level:

    CREATE TABLE testing
    (
        cola int NOT NULL,
        colb CHAR(1) NOT NULL
    );
    
    CREATE UNIQUE INDEX UIX_testing_a ON testing(colb);
    
    INSERT INTO testing VALUES (1, 'b');
    INSERT INTO testing VALUES (2, 'a');
    
    SELECT * FROM testing;
    
    UPDATE testing
    SET colb = CASE cola WHEN 1 THEN 'a'
                    WHEN 2 THEN 'b'
                    END
    WHERE cola IN (1,2);
    
    SELECT * FROM testing;
    

    so you will go from:

    cola    colb
    ------------
    1       b
    2       a
    

    to:

    cola    colb
    ------------
    1       a
    2       b
    

提交回复
热议问题