Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 对Select查询中的所有列执行函数_Sql_Postgresql_Psycopg2 - Fatal编程技术网

Sql 对Select查询中的所有列执行函数

Sql 对Select查询中的所有列执行函数,sql,postgresql,psycopg2,Sql,Postgresql,Psycopg2,我定义了此函数,用于修剪尾随空格: create or replace function trim_trailing_whitespace(value text) returns text as $$ begin return regexp_replace(value, '\s+$', ''); end; $$ language plpgsql immutable; 在类似这样的查询中使用时,它可以正常工作: select trim_trailing_whitespace(SomeColumn

我定义了此函数,用于修剪尾随空格:

create or replace function trim_trailing_whitespace(value text) returns text as $$ begin return regexp_replace(value, '\s+$', ''); end; $$ language plpgsql immutable;
在类似这样的查询中使用时,它可以正常工作:

select trim_trailing_whitespace(SomeColumn), count(*) from MyTable group by SomeColumn;
但是,当我尝试使用通配符时,它失败了,如下所示:

select trim_trailing_whitespace(*) from MyTable;
第1行:从MyTable中选择trim_training_whitespace(*)

提示:没有与给定名称和参数类型匹配的函数。您可能需要添加显式类型转换


如何对select查询中的所有列执行函数?在我的例子中,我想在执行选择时删除每列的尾随空格。

如果可能,请定义第二个
变量
版本的函数。使用
FOREACH
迭代args,并对每个参数执行当前函数


这里有一个很好的例子:

您可以使用动态sql或手动展开
*

SELECT FORMAT(
  'SELECT %s FROM %I.%I.%I;',
  string_agg(
    FORMAT(
      'trim_trailing_whitespace(%I)',
      column_name
    ),
    ', '
  )
  , table_catalog, table_schema, table_name
)
FROM information_schema.columns
WHERE table_catalog = current_catalog
  AND table_schema = current_schema
  AND table_name = 'MyTable'
GROUP BY table_catalog, table_schema, table_name;

或者使用row_to_json将数据作为json传递进来。。。请记住,除非您的函数返回特定类型的行,否则考虑到它的使用方式,json可能是最好的选择之一。这似乎很有希望,但我无法使它处理具有多个列的行。在我运行它时,这只是不返回任何内容。您是否用表名替换了
MyTable
。还是没有结果。为了清楚起见,我想在返回每一行中的每一列之前将此函数应用于每一行中的每一列。它不返回任何内容,就像不返回任何行或列一样。没有错误。它返回您需要的SQL。您必须运行该SQL<代码>\gset foo<代码>\gexec foo如果您使用的是psql