通过动态查询

时间:2015-11-25 13:19:35

标签: postgresql plpgsql postgresql-9.5

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

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;

当表不存在时,此函数也可以工作,也可以创建表索引,但是当表和索引已经存在时,会抛出通知:relation "t" already exists和错误: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;

1 个答案:

答案 0 :(得分: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;

阅读:Control Structures