如何在plpgsql中编写更新语句

问题描述 投票:0回答:1

我刚刚在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();
postgresql plpgsql dynamic-sql
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.