i want to create table if that doesn't, i tried below code:
create or replace function create_table() returns void as
$$
begin
if not exists(select *
from pg_tables
where schemaname = 'Public'
and tablename = 'test')
then
create table test
(
the_id int not null,
name text
);
end if;
end;
$$
language 'plpgsql';
While executing this procedure first time:
select creat_table();
table gets created but when I execute it again I get the below error:
ERROR: relation "test" already exists
CONTEXT: SQL statement "create table test
(
the_id int not null,
name text
)"
PL/pgSQL function create_table() line 8 at SQL statement
********** Error **********
ERROR: relation "test" already exists
SQL state: 42P07
Context: SQL statement "create table test
(
the_id int not null,
name text
)"
PL/pgSQL function create_table() line 8 at SQL statement
How to achieve this, and also I want to call this procedure from Informatica pre-sql target session property so i want to call procedure with table name as parameter.
Best Answer
Just use
CREATE TABLE [IF NOT EXISTS]
Looks like this,
If you must wrap it in a function (don't though, there is no point),
If you want that function to accept a name (still wouldn't suggest this),
[ IF NOT EXISTS ]
has been in PostgreSQL since 9.1