Postgresql 如何在plpgsql中编写update语句
我刚刚完成了plsql的第一步。我想在所有表上循环,如果某个字段有某个旧值,则更改该字段。 不幸的是,我真的不知道如何在update语句中转义我的值并获得错误消息 “第16行“=”处或附近出现语法错误” 以下哪一行是:Postgresql 如何在plpgsql中编写update语句,postgresql,plpgsql,dynamic-sql,Postgresql,Plpgsql,Dynamic Sql,我刚刚完成了plsql的第一步。我想在所有表上循环,如果某个字段有某个旧值,则更改该字段。 不幸的是,我真的不知道如何在update语句中转义我的值并获得错误消息 “第16行“=”处或附近出现语法错误” 以下哪一行是: execute 'update xyz.' || info || 'set update_date = 2010-11-17 17:00:00 where update_date =2010-11-16 17:00:00'; 您可以使用executeformat简化upd
execute 'update xyz.' || info || 'set
update_date = 2010-11-17 17:00:00 where update_date =2010-11-16 17:00:00';
您可以使用
executeformat
简化update语句
要检查update语句是否修改了一行的值,可以使用
行计数
诊断
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;
另一方面,与其返回逗号分隔的更新表字符串,不如返回数组
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;