Swap unique indexed column values in database

前端 未结 12 956
伪装坚强ぢ
伪装坚强ぢ 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:47

    There is another approach that works with SQL Server: use a temp table join to it in your UPDATE statement.

    The problem is caused by having two rows with the same value at the same time, but if you update both rows at once (to their new, unique values), there is no constraint violation.

    Pseudo-code:

    -- setup initial data values:
    insert into data_table(id, name) values(1, 'A')
    insert into data_table(id, name) values(2, 'B')
    
    -- create temp table that matches live table
    select top 0 * into #tmp_data_table from data_table
    
    -- insert records to be swapped
    insert into #tmp_data_table(id, name) values(1, 'B')
    insert into #tmp_data_table(id, name) values(2, 'A')
    
    -- update both rows at once! No index violations!
    update data_table set name = #tmp_data_table.name
    from data_table join #tmp_data_table on (data_table.id = #tmp_data_table.id)
    

    Thanks to Rich H for this technique. - Mark

提交回复
热议问题