UPDATE with ORDER BY

后端 未结 6 2311
Happy的楠姐
Happy的楠姐 2020-12-11 01:30

Need to "tie" UPDATE with ORDER BY. I\'m trying to use cursors, but get the error:

cursor "cursupd"         


        
6条回答
  •  一生所求
    2020-12-11 02:12

    If anyone comes here just like I came for the problem with rearranging the postgresql table_id_seq from 1 and order by the id. The solution I tried was partially taken from @Syd Nazam Ul Hasan (above) and https://gist.github.com/JoshCheek/e19f83f271dc16d7825e2e4079538ba8.

    CREATE OR REPLACE FUNCTION update_sequence()
    RETURNS SETOF varchar AS $$
    DECLARE
      curs CURSOR FOR SELECT * FROM table ORDER BY id ASC;
      row  RECORD;
      v INTEGER := 0;
    BEGIN
      open curs;
      LOOP
        FETCH FROM curs INTO row;
        update table 
        set id = v+1
        where id = row.id;
        v = v+1;
        EXIT WHEN NOT FOUND;
        return next row.id;
      END LOOP;
    END; $$ LANGUAGE plpgsql;
    
    SELECT update_sequence();
    

提交回复
热议问题