UPDATE with ORDER BY

后端 未结 6 2315
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:07

    Lazy Way, (aka not fastest or best way)

    CREATE OR REPLACE FUNCTION row_number(table_name text, update_column text, start_value integer, offset_value integer, order_by_column text, order_by_descending boolean)
      RETURNS void AS
    $BODY$
    DECLARE
        total_value integer;
        my_id text;
        command text;
    BEGIN
    total_value = start_value;
        command = 'SELECT ' || order_by_column || ' FROM ' || table_name || ' ORDER BY '  || order_by_column;
    
        if (order_by_descending) THEN
            command = command || ' desc';
        END IF;
    
        FOR  my_id in  EXECUTE command LOOP
            command = 'UPDATE ' || table_name || ' SET  ' || update_column || ' = ' || total_value || ' WHERE ' || order_by_column || ' = ' ||  my_id|| ';';
    
            EXECUTE command;
            total_value = total_value + offset_value;
        END LOOP;
    END;
    $BODY$
      LANGUAGE 'plpgsql' VOLATILE
      COST 100;
    

    Example

    SELECT row_number('regispro_spatial_2010.ags_states_spatial', 'order_id', 10,1, 'ogc_fid', true)

提交回复
热议问题