как написать инструкцию обновления в plpgsql

#postgresql #plpgsql #dynamic-sql

#postgresql #plpgsql #динамический-sql

Вопрос:

Я только что сделал свои самые первые шаги в plsql. Я хочу перебрать все таблицы и изменить определенное поле, если оно имеет определенное старое значение. К сожалению, я действительно не знаю, как избежать моих значений в моем операторе обновления и получить сообщение об ошибке.

«синтаксическая ошибка в или рядом » =» в строке 16″,

какая следующая строка:

 execute 'update xyz.' || info || 'set 
 update_date = 2010-11-17 17:00:00 where update_date =2010-11-16 17:00:00';
  

 create or replace function test() returns text as $$

declare 
re text default '';
info text;
cur_tables cursor for select  table_name FROM 
information_schema.tables WHERE table_schema = 'xyz';
begin

open cur_tables;

fetch next from cur_tables into info;

while (found) loop
        re := re|| ',' ||info;

    execute 'update xyz.' || info 
  || 'set update_date = 2010-11-17 17:00:00 where update_date =2010-11-16 17:00:00';
    fetch next from cur_tables into info;
    end loop;


return re;
end; $$

language plpgsql;

select test();
  

Ответ №1:

Вы можете использовать execute format для упрощения инструкции обновления.

Чтобы проверить, изменил ли оператор update значение хотя бы одной строки, вы можете использовать ROW_COUNT DIAGNOSTICS

 create or replace function test() returns text as $$
declare 
  cur RECORD;
  ct int;
  re text default '';
begin

for cur in ( select  table_name FROM information_schema.tables 
             WHERE table_schema = 'xyz' )
LOOP
    EXECUTE format( 'update xyz.%I set update_date = %L where update_date = %L',
                     cur.table_name,'2010-11-17 17:00:00','2010-11-16 17:00:00') ;

    GET DIAGNOSTICS ct = ROW_COUNT; --get number of rows affected by the 
                                --previous statement.

  IF ct > 0 THEN
    re := re|| ',' ||cur.table_name;
  END IF;

END LOOP;

return trim(BOTH ','  from re);
end; $$

language plpgsql;
  

Кстати, вместо возврата строки обновленных таблиц, разделенных запятыми, предпочтительнее возвращать array вместо.