简体   繁体   English

调试PL / pgSQL函数

[英]Debugging a PL/pgSQL function

I am trying to get this PL/pgSQL function to work : 我正在尝试使此PL / pgSQL函数正常工作:

CREATE OR REPLACE FUNCTION loopcolumns2(tableName TEXT, pourcentage real)
RETURNS void AS $$
DECLARE 
    _name text; 
    missing_percentage real;
BEGIN
    FOR _name IN SELECT column_name from information_schema.columns where table_name=tableName LOOP
        SELECT 100 - (count(_name) * 100) / count(*) INTO missing_percentage FROM tableName;
        IF (missing_percentage > pourcentage)
            THEN ALTER TABLE tableName DROP COLUMN _name;
        END IF;
    END LOOP;
END; $$ LANGUAGE plpgsql;

The goal of the function is to loop through all the columns of a table, a delete the columns where the percentage of missing values is bigger than an input percentage. 该功能的目标是遍历表的所有列,删除缺失值百分比大于输入百分比的列。

I get the following error : 我收到以下错误:

SELECT 100 - (count( $1 ) * 100) / count(*) FROM  $2
                                                  ^
CONTEXT:  SQL statement in PL/PgSQL function "loopcolumns2" near line 6

You're trying to SELECT from text stored by tableName vaiable. 您正在尝试从由tableName可用存储的文本中进行SELECT You cannot do that because Postgres think you want him to select from table named tableName , but probably such table doesn't exist. 您不能这样做,因为Postgres认为您希望他从名为tableName表中进行选择,但这种表可能不存在。

You nead to create dynamic query in string and use EXECUTE ... INTO ... statement . 您需要在字符串中创建动态查询并使用EXECUTE ... INTO ...语句 Like this: 像这样:

DECLARE query TEXT;
...

query :=  'SELECT 100 - (count(' || _name::TEXT || ') * 100) / count(*) FROM '
          || tableName::TEXT;

EXECUTE query INTO percentage ;
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM