How to run an ad-hoc script in PostgreSQL?

僤鯓⒐⒋嵵緔 提交于 2019-11-28 19:44:30

问题


I'm trying to run this in PostgreSQL 9.2:

RAISE NOTICE 'hello, world!';

And the server says:

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

Why?


回答1:


Use an anonymous code block:

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

Variables are referenced using %:

RAISE NOTICE '%', variable_name;



回答2:


raise is PL/pgSQL only.

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



回答3:


simple example:

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;


来源:https://stackoverflow.com/questions/18828127/how-to-run-an-ad-hoc-script-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!