如何在plpgsql中编写更新语句

时间:2019-04-14 12:05:12

标签: postgresql plpgsql dynamic-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 个答案:

答案 0 :(得分:1)

您可以使用execute format来简化更新语句。

要检查更新语句是否修改了偶数行的值,可以使用 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