1

我需要动态创建表,在此之后,我还需要在该表上创建索引

CREATE OR REPLACE FUNCTION test_func() RETURNS void 
as
$$
begin
EXECUTE 'CREATE TABLE IF NOT EXISTS t(field  int)';

EXECUTE 'create unique index index_name on t(field)';

EXECUTE 'INSERT INTO t(field) values(1)';
end;
$$ language plpgsql;

当表不存在时,此函数起作用,也为表创建索引,但是当表和索引已经存在时,会抛出 notice:relation "t" already exists和 error: relation "index_name" already exists

所以,我需要从第一个查询中捕获异常并且不创建索引,如果捕获通知:table already exists

也就是说,如何做这样的事情?

begin
EXECUTE 'CREATE TABLE IF NOT EXISTS t(field  int)';

IF HERE NOT CATCHED NOTICE 'relation "t" already exists' THEN

EXECUTE 'create unique index index_name on t(field)';

END IF;

EXECUTE 'INSERT INTO t(field) values(1)';
end;
4

1 回答 1

2

使用异常块:

CREATE OR REPLACE FUNCTION test_func() 
RETURNS void as $$
begin
    EXECUTE 'CREATE TABLE IF NOT EXISTS t(field  int)';
    BEGIN
        EXECUTE 'create unique index index_name on t(field)';
    EXCEPTION WHEN duplicate_table THEN
        -- do nothing
    END;
    EXECUTE 'INSERT INTO t(field) values(1)';
end;
$$ language plpgsql;

阅读:控制结构

于 2015-11-25T13:50:29.347 回答