将异常错误插入表中

时间:2015-08-06 04:07:53

标签: sql postgresql postgresql-9.3

我有这样的代码:

do $$
begin
    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

    create table y(b varchar(250));

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

--insert into y select  -- This line doesn't work.  
    raise notice '% %', SQLERRM, SQLSTATE;
end;


$$ language 'plpgsql';

我想将引起的错误插入Y表。

我该怎么做?

我想将NOTICE: relation "yyy" already exists 42P07插入Y表。

1 个答案:

答案 0 :(得分:0)

您可能希望在单独的脚本中创建表Y,因此它在引发异常之前就存在了。

create table y(b varchar(250));

您可以在不创建表Y的情况下在单独的块中执行命令。像这样:

begin
    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 
    raise notice 'The transaction is in an uncommittable state. '
             'Transaction was rolled back';
    insert into y(b) values('NOTICE:  relation "yyy" already exists 42P07');
    raise notice '% %', SQLERRM, SQLSTATE;
end;