Shift (update) unique column values in PostgreSQL

后端 未结 2 1973
星月不相逢
星月不相逢 2021-01-13 06:40

Using MS SQL Server, the following works fine:

CREATE TABLE #temptable(mykey int primary key)

INSERT INTO #temptable VALUES (1)
INSERT INTO #temptable VALUE         


        
2条回答
  •  伪装坚强ぢ
    2021-01-13 06:53

    This is indeed a bit confusing as all other constraints are evaluated on a statement level, only PK/unique constraint are evaluated on a per row level during DML operations.

    But you can work around that by declaring the primary key constraint as deferrable:

    create table tbl_test 
    (
      testkey   INTEGER,
      constraint pk_tbl_test primary key (testkey) deferrable initially immediate
    );
    
    insert into tbl_test values (1), (2);
    
    set constraints all deferred;
    
    update tbl_test
       set testkey = testkey +1;
    

    Deferred constraints do have some overhead, so by defining it as initially immediate this overhead is kept to a minimum. You can the defer the constraint evaluation when you need it by using set constraint.


    The real question however is: why would you need to do this on a primary key value? The PK values has no meaning whatsoever, so it seems rather unnecessary to increment all values (regardless of the DBMS being used)

提交回复
热议问题