如何在PostgreSQL中运行ad-hoc脚本?

时间:2013-09-16 12:31:30

标签: postgresql postgresql-9.2

我正试图在PostgreSQL 9.2中运行它:

RAISE NOTICE 'hello, world!';

服务器说:

Error : ERROR:  syntax error at or near "RAISE"
LINE 1: RAISE NOTICE 'hello, world!'
        ^

为什么?

3 个答案:

答案 0 :(得分:70)

使用匿名code block

DO language plpgsql $$
BEGIN
  RAISE NOTICE 'hello, world!';
END
$$;

Variables are referenced使用%

RAISE NOTICE '%', variable_name;

答案 1 :(得分:21)

raise仅限PL/pgSQL

http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html

create or replace function r(error_message text) returns void as $$
begin
    raise notice '%', error_message;
end;
$$ language plpgsql;

select r('an error message');
NOTICE:  an error message

答案 2 :(得分:0)

简单的例子:

CREATE OR REPLACE FUNCTION test()     
RETURNS TRIGGER AS
'
DECLARE


num int;

 BEGIN
IF TG_OP = ''INSERT'' THEN
select count(*) into num from test_table;
IF num >= 1 THEN
RAISE WARNING ''Cannot Insert more than one row'';
RETURN OLD;
END IF;
ELSE
RETURN NEW;
END IF;

END;
' LANGUAGE plpgsql;