如何在plpgsql中写更新语句
how to write a update statement in plpgsql
我刚刚完成了 plsql 的第一步。我想遍历所有表并更改某个字段(如果它具有某个旧值)。
不幸的是,我真的不知道如何在我的更新语句中转义我的值并得到一条错误消息。
"syntax error at or near "=" at line16",
也就是下面一行:
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();
您可以使用 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;
附带说明一下,不是 return 更新表的逗号分隔字符串,而是 return 和 array
更可取。
我刚刚完成了 plsql 的第一步。我想遍历所有表并更改某个字段(如果它具有某个旧值)。 不幸的是,我真的不知道如何在我的更新语句中转义我的值并得到一条错误消息。
"syntax error at or near "=" at line16",
也就是下面一行:
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();
您可以使用 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;
附带说明一下,不是 return 更新表的逗号分隔字符串,而是 return 和 array
更可取。