将plpgsql var与游标语句

时间:2015-04-29 15:18:08

标签: sql database postgresql plpgsql postgresql-9.3

我在第二次尝试连接var sch时出错:

  

错误:“||”中或下一个语法错误   SQL状态:42601   性格:1151

有谁知道如何解决这个问题连接?

CREATE OR REPLACE FUNCTION generate_mallet_input2() RETURNS VOID AS $$ 
DECLARE 
sch name;
r record;   
BEGIN

    FOR sch IN 
     select schema_name from information_schema.schemata where schema_name not in ('test','summary','public','pg_toast','pg_temp_1','pg_toast_temp_1','pg_catalog','information_schema') 
    LOOP 
         FOR r IN SELECT rp.id as id,g.classified as classif, concat(rp.summary,rp.description,string_agg(c.message, '. ')) as mess
            FROM  sch.report rp
            INNER JOIN || sch || .report_comment rc ON rp.id=rc.report_id
            INNER JOIN || sch || .comment c ON rc.comments_generatedid=c.generatedid 
            INNER JOIN || sch || .gold_set g ON rp.id=g.key
            WHERE g.classified = any (values('BUG'),('IMPROVEMENT'),('REFACTORING'))
            GROUP BY g.classified,rp.summary,rp.description,rp.id
         LOOP

            IF r.classif = 'BUG' THEN
                EXECUTE 'Copy( Values('|| r.mess  || ') ) To ''/tmp/csv-temp/BUG/' || quote_ident(sch) || '-' || r.id || '.txt '' With DELIMITER '' '' ';
            ELSIF r.classif = 'IMPROVEMENT' THEN
                EXECUTE 'Copy( Values('|| r.mess  || ') ) To ''/tmp/csv-temp/IMPROVEMENT/' || quote_ident(sch) || '-' || r.id || '.txt '' With DELIMITER '' '' ';
            ELSIF r.classif = 'REFACTORING' THEN
                EXECUTE 'Copy( Values('|| r.mess  || ') ) To ''/tmp/csv-temp/REFACTORING/' || quote_ident(sch) || '-' || r.id || '.txt '' With DELIMITER '' '' ';
            END IF;             

         END LOOP;



    END LOOP; 
    RETURN; 

END;
$$ LANGUAGE plpgsql STRICT; 

1 个答案:

答案 0 :(得分:1)

您无法动态更改嵌入式SQL的架构。任何与数据库相关的标识符必须是常量。如果您有一些现代的PostgreSQL(可能高于9.2,在9.4中工作),您可以更改搜索路径:

create schema s1;
create schema s2;
create table s1.t1(a int);
create table s2.t1(a int);
insert into s1.t1 values(10);
insert into s2.t1 values(20);

do $$
declare r record;
begin
  for  i in 1..2 loop
    perform set_config('search_path', 's'||i, true);
    for r in select * from t1 loop 
      raise notice '%', r;
    end loop;
  end loop; 
end; $$;

如果此代码不起作用,则必须使用动态SQL - FOR IN EXECUTE语句。