postgresql 如何在不创建函数的情况下执行 pl/pgsql 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2569504/
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 can I execute pl/pgsql code without creating a function?
提问by Jeremiah Peschka
With SQL Server, I can execute code ad hoc T-SQL code with full procedural logic through SQL Server Management Studio, or any other client. I've begun working with PostgreSQL and have run into a bit of a difference in that PGSQL requires any logic to be embedded in a function.
使用 SQL Server,我可以通过 SQL Server Management Studio 或任何其他客户端执行具有完整过程逻辑的代码即席 T-SQL 代码。我已经开始使用 PostgreSQL 并且遇到了一些不同之处,即 PGSQL 需要将任何逻辑嵌入到函数中。
Is there a way to execute PL/PGSQL code without creating an executing a function?
有没有办法在不创建执行函数的情况下执行 PL/PGSQL 代码?
回答by chotchki
Postgres 9
Postgres 9
DO $$
-- declare
BEGIN
/* pl/pgsql here */
END $$;
回答by Frank Heikens
No, not yet. Version 9.0 (still alpha) will have this option (do), you a have to wait until it's released.
还没有。版本 9.0(仍然是 alpha)会有这个选项(做),你必须等到它发布。
回答by Davos
I struggled to get this working because it's fairly strict about adding semi colons in exactly the right places. But once you get used to that it works well. Besides the inability to return records of course, however you can raise notices & exceptions and do the other workarounds like using temp tables as @ErwinBrandstetter pointed out in a comment above.
我努力让它工作,因为在正确的地方添加分号是相当严格的。但是一旦你习惯了,它就会很好地工作。当然,除了无法返回记录之外,您还可以提出通知和异常,并执行其他解决方法,例如使用 @ErwinBrandstetter 在上面的评论中指出的临时表。
e.g.:
例如:
DO
$$
BEGIN
IF EXISTS(SELECT 'any rows?'
FROM {your_table}
WHERE {your_column} = 'blah')
THEN
RAISE NOTICE 'record exists';
ELSE
RAISE EXCEPTION 'record does not exist';
END IF;
DROP TABLE IF EXISTS foo;
CREATE TEMP TABLE foo AS
SELECT 'bar'::character varying(5) as baz;
END
$$;
SELECT * FROM foo;