Swap unique indexed column values in database

前端 未结 12 975
伪装坚强ぢ
伪装坚强ぢ 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 07:00

    Further to Andy Irving's answer

    this worked for me (on SQL Server 2005) in a similar situation where I have a composite key and I need to swap a field which is part of the unique constraint.

    key: pID, LNUM rec1: 10, 0 rec2: 10, 1 rec3: 10, 2

    and I need to swap LNUM so that the result is

    key: pID, LNUM rec1: 10, 1 rec2: 10, 2 rec3: 10, 0

    the SQL needed:

    UPDATE    DOCDATA    
    SET       LNUM = CASE LNUM
                  WHEN 0 THEN 1
                  WHEN 1 THEN 2 
                  WHEN 2 THEN 0 
              END
    WHERE     (pID = 10) 
      AND     (LNUM IN (0, 1, 2))
    

提交回复
热议问题