Postgresql:获取列名称为

rkkpypqq  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(129)

我不是SQL和PostgreSQL的Maven。我需要从列名包含字符串的表中获取所有行。为了得到好列的列表,我使用

SELECT column_name FROM information_schema.columns WHERE table_schema = 'myschema'
AND table_name = 'mytable' AND column_name like 'AB%'

或者更专业地说:https://dba.stackexchange.com/a/246996
但是当我想用下面的查询获取数据时,我遇到了错误:ERROR: more than one row returned by a subquery used as an expression

SELECT 
  (SELECT 
      column_name 
   FROM 
      information_schema.columns WHERE table_schema = 'myschema' AND 
      table_name = 'mytable' AND column_name LIKE 'AB%'
   ) AS AB 
 FROM 
     myschema.mytable

我的错误在哪里?谢谢

a9wyjsp7

a9wyjsp71#

你可以通过一个使用动态查询的函数来实现这一点,就像这样:

create or replace function myfunction()
returns setof varchar as 
$$
declare
  l_column varchar;
begin   
    --get the column name
    select column_name into l_column 
    from information_schema.columns 
    where table_schema = 'myschema'
    and table_name = 'mytable' and column_name like 'AB%';
   -- dynamic query passing column name
   return query execute format('select %I '
   'from myschema.mytable', l_column);   
end; 
$$ language plpgsql;

然后

select myfunction();

这是一个返回列的例子,更多信息请查看官方文档

相关问题