如何在 PostgreSQL 中运行临时脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18828127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run an ad-hoc script in PostgreSQL?
提问by yegor256
I'm trying to run this in PostgreSQL 9.2:
我正在尝试在 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?
为什么?
回答by Tomas Greif
Use an anonymous code block:
使用匿名代码块:
DO language plpgsql $$
BEGIN
RAISE NOTICE 'hello, world!';
END
$$;
Variables are referencedusing %
:
使用%
以下方法引用变量:
RAISE NOTICE '%', variable_name;
回答by Clodoaldo Neto
raise
is PL/pgSQL
only.
raise
是PL/pgSQL
唯一的。
http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html
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
回答by Mehdi Sadighian
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;