在PostgreSQL中选择具有特定列名称的列

And*_*nov 6 sql database postgresql select dynamic-sql

我想编写一个简单的查询来选择PostgreSQL中的多个列.但是,我一直在收到错误 - 我尝试了一些选项,但它们对我不起作用.目前我收到以下错误:

org.postgresql.util.PSQLException:错误:"列"或附近的语法错误

要获取具有值的列,请尝试以下操作:

select * from weather_data where column like '%2010%'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Erw*_*ter 9

column是一个保留字.除非您双引号,否则不能将其用作标识符.喜欢:"column".

但这并不意味着你应该这样做.只是不要使用保留字作为标识符.永远.

至 ...

选择名称中包含2010的列列表:

..您可以使用此函数从系统目录表pg_attribute动态构建SQL命令:

CREATE OR REPLACE FUNCTION f_build_select(_tbl regclass, _pattern text)
  RETURNS text AS
$func$
    SELECT format('SELECT %s FROM %s'
                 , string_agg(quote_ident(attname), ', ')
                 , $1)
    FROM   pg_attribute 
    WHERE  attrelid = $1
    AND    attname LIKE ('%' || $2 || '%')
    AND    NOT attisdropped  -- no dropped (dead) columns
    AND    attnum > 0;       -- no system columns
$func$ LANGUAGE sql;
Run Code Online (Sandbox Code Playgroud)

呼叫:

SELECT f_build_select('weather_data', '2010');
Run Code Online (Sandbox Code Playgroud)

返回类似于:

SELECT foo2010, bar2010_id, FROM weather_data;
Run Code Online (Sandbox Code Playgroud)

您无法使其完全动态化,因为在我们实际构建查询之前,返回类型是未知的.

  • Em,我实际上没有 - 我只是想搜索 2010 作为其名称一部分的列名,而不是名为 column 的列,其中 2010 作为其中一个值的一部分...... (2认同)

sge*_*des 6

这将获取特定表中的列列表(如果需要,您可以选择添加模式):

SELECT column_name
FROM information_schema.columns
WHERE table_name = 'yourtable'
  and column_name like '%2010%'
Run Code Online (Sandbox Code Playgroud)

SQL小提琴演示

然后,您可以使用该查询创建动态sql语句以返回结果.