Postgres:如何在循环中打印值
问题描述:
我想打印从查询中获得的所有表格。但是,我的代码只显示该函数的名称。Postgres:如何在循环中打印值
# create or replace function remove_scene()
# RETURNS void AS $$
# DECLARE
# row record;
# BEGIN
# FOR row IN
# select table_name from information_schema.tables WHERE table_schema = 'public' AND table_name ~ 'measurement[0-9]'
# LOOP
# RAISE NOTICE '** %', quote_ident(row.table_name);
# END LOOP;
# END;
# $$ LANGUAGE plpgsql;
CREATE FUNCTION
# select remove_scene();
remove_scene
--------------
(1 row)
#
答
你没有看到任何东西的原因是你的函数没有返回任何东西。使用RAISE NOTICE
“写入”的文本将仅在客户端显示,如果a)客户端支持(psql)和b)如果您的会话配置为实际返回它们。为了在psql
可以看到你加薪,你需要使用:
set client_min_messages = NOTICE;
您目前的设定可能是WARNING
,并且因而不显示NOTICE
。
但是:在RAISE NOTICE
的循环中这样做效率很低。这将是更好的改变你的功能分为一组返回函数:
create or replace function remove_scene()
RETURNS table(table_name text)
AS $$
select table_name
from information_schema.tables
WHERE table_schema = 'public'
AND table_name ~ 'measurement[0-9]'
$$
LANGUAGE sql;
,然后用它是这样的:
select *
from remove_scene();
另一种办法是把那个select语句到视图。