Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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
Function PL/pgSQL函数工作不正常_Function_Postgresql_Plpgsql_Exists - Fatal编程技术网

Function PL/pgSQL函数工作不正常

Function PL/pgSQL函数工作不正常,function,postgresql,plpgsql,exists,Function,Postgresql,Plpgsql,Exists,我正在编写一个函数来为给定的表计数创建表。在创建特定表之前,我要检查该表是否已存在: create or replace function test (numoftables int) returns void as $$ declare i integer; begin i:=0; while i< numoftables loop if not exists (select * from table$i$) -- check

我正在编写一个函数来为给定的表计数创建表。在创建特定表之前,我要检查该表是否已存在:

create or replace function test (numoftables int) returns void as $$
    declare
    i integer;
    begin 
    i:=0;
    while i< numoftables loop
        if not exists (select * from table$i$)  -- check if table exists
        then 
            create table table$i$(
                column1 int,
                column2 int,
                column1 text,
                column2 text,
                column3 text); 
        end if;
    end loop;
end;

$$
language 'plpgsql';
有人能告诉我如何更改此代码以正常工作吗

你不能像这样检查表的存在。使用系统表检查表是否存在 你必须在你的函数中增加i,否则你会得到无限循环 我试着不改变你的逻辑或语法太多,所以它仍然是你的功能


语言名称是一个常规SQL标识符,这意味着您不应该将其放在单引号中。请改用语言plpgsql。将来可能会删除对单引号语言名称的支持。顺便说一句:如果不存在,为什么不使用CREATETABLE。。。?
ERROR:  relation "table$i$" does not exist
LINE 1: SELECT not exists (select * from table$i$)
create or replace function test (numoftables int) returns void as $$
    declare
    i integer;
    begin 
    i:=0;
    while i< numoftables loop
        if not exists (select * from pg_class where relname = 'table' || i::text)
        then
            execute '
            create table table' || i::text || '(
                column1 int,
                column2 int,
                column3 text,
                column4 text,
                column5 text);
            ';
        end if;
        i := i + 1;
    end loop;
end;

$$
language 'plpgsql';