0

如果我将这两个 Postgres 函数定义保存在两个单独的 .sql 文件中:

CREATE OR REPLACE FUNCTION column_exists(tablename text, colname text) RETURNS boolean AS 
        $BODY$
        DECLARE
            q text;
            field_name text;
            onerow record;
        BEGIN
            q = 'SELECT column_name FROM information_schema.columns WHERE table_name='''||tablename||''' AND table_schema =''public''';
            FOR onerow IN EXECUTE q
                LOOP
                   field_name := onerow.column_name;
                   IF ((field_name = colname)) then
                    RETURN true;
                   END IF;                  
                END LOOP;
            RETURN false;
        END;
    $BODY$
LANGUAGE plpgsql
CREATE OR REPLACE FUNCTION correct_col_names() RETURNS VOID AS
    $BODY$
        DECLARE
            q boolean;
        BEGIN                       

             -- rename name column to Name
             select column_exists('National_Parks', 'name') as q;
             IF q = TRUE THEN
            alter table "National_Parks"
            rename column name to "Name";
             END IF;    

             -- remance descriptio column to description
             select column_exists('National_Parks', 'descriptio') as q;
             IF q = TRUE THEN
            alter table "Natioanl_Parks"
            rename column descriptio to "Description";
             END IF;    

        END
    $BODY$
LANGUAGE plpgsql

我需要使用什么语法来顺序调用,比如在另一个脚本中?我试过

select correct_col_names()

这将返回以下错误:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function "correct_col_names" line 7 at SQL statement

********** Error **********

ERROR: query has no destination for result data
SQL state: 42601
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Context: PL/pgSQL function "correct_col_names" line 7 at SQL statement

TIA。

4

1 回答 1

3

问题是您的 SELECT 语句没有对数据做任何事情。您的

select column_exists('National_Parks', 'name') as q;

应该

select column_exists('National_Parks', 'name') INTO q;

只是将该as查询的结果别名为“q”,它实际上并没有将其放入 q 变量中。

您调用函数 ( select correct_col_names()) 的语法对于 SQL 是正确的。一旦您修复了该函数中的两个错误,它应该可以工作。

然而,如果你在另一个 PL/PGSQL 函数中尝试select correct_col_names(),你会得到同样的错误,因为 select 语句实际上并没有对结果任何事情。 perform correct_col_names()运行不会出错,因为 PERFORM 是 PL/PGSQL 语法,用于在您不想保存结果时调用某些内容。

于 2012-12-11T19:51:17.123 回答