Doubt in Postgresql function

Asked

Viewed 44 times

2

I am doing a function in Postgresql and I want to use it to check if a table already exists or not in a database and, if not, I want to create a table.

The problem is in the function declaration, which receives a varchar, parameter that will be used for the SELECT relname and also for the create table.

Follows the function:

CREATE OR REPLACE FUNCTION verificarDb (tb varchar)RETURNS BOOLEAN as
$$
BEGIN
select relname from pg_class where relname = tb and relkind='r';
if not found then
        CREATE TABLE tb
        (
          id integer,
          nome varchar
        );
    return false;
end if;
if found then
return true;
end if; 
END;
$$
LANGUAGE plpgsql;
select verificarDb('tabela');

The check is not being done by the contents of the parameter tb, but using the string tb. In the create is also using the acronym tb, I want to use the table name passed by parameter, as I do?

2 answers

3


I managed to complete the function, follows below as the sketch of the code:

    CREATE OR REPLACE FUNCTION verificarDb (tb varchar)RETURNS BOOLEAN as
    $$
    DECLARE result boolean;
    BEGIN
     execute format ('SELECT EXISTS (select 1 from pg_class where relname = 
    ''%s'' and relkind=''r'');', tb)
    INTO result;
    if result = FALSE then
      EXECUTE format ('CREATE TABLE "%s"
      (
        id integer,
        nome varchar
      );', tb);

        RETURN FALSE;
      ELSE
        RETURN TRUE;
      end if; 
     END;
     $$
     LANGUAGE plpgsql;
     --teste de função -> select verificarDb('tabela');

1

Experiment as follows:

CREATE OR REPLACE FUNCTION verificarDb(tb regclass, OUT result boolean) AS
$$
BEGIN
    EXECUTE format('SELECT EXISTS   (
                                        SELECT 1 
                                        FROM   pg_class c
                                        WHERE  relname = ''%s''
                                        AND    c.relkind = ''r''
                                    );', tb)
    INTO result;

    IF result = FALSE THEN
        CREATE TABLE tb
        (
          id    INTEGER,
          nome  VARCHAR
        );
    END IF;
END;
$$  
LANGUAGE plpgsql;

Form of use:

SELECT verificarDb('tabela');

Since I come from SQL Server, syntax and structure may have to be adjusted, but I think it won’t be difficult.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.