8

I am new to PostgreSQL and am using the query tool in PGAdmin. I'm trying to run pgsql queries that use variables, but I can't seem to get the syntax right.

Here's a sample query that gives a syntax error:

DECLARE
  num INTEGER;

BEGIN

  num := 3;
  PRINT num;

END;

Update:
Ok, let me try and explain. I come from a SQL server background. In the management studio, I can open a query window and play with (T)-SQL queries.

For example, I can write something like this:

DECLARE @num INT
SET @num = 3
SELECT @num

I know this is a dumb example, but I'm just trying to declare a variable and do something with it. I'm trying to familiarise myself with PL/PGSQL.


Update, again:
It's me again. I'm trying the script below and get a "[ERROR ] 7.0-2: syntax error, unexpected character". Is this meant to work in PGAdmin?

DECLARE
  num INTEGER;

BEGIN

  num := 3;
  RAISE NOTICE '%', num;

END;
4

5 回答 5

12

您可以使用 do 语句。例如:

do $$
declare 
  num integer := 10;
begin

    RAISE INFO 'VARIABLE: %', num;

end;
$$language plpgsql;

当您使用 pgadmin 时,您必须使用按钮 EXECUTE QUERY 而不是 Execute pdScript,如下所述:

http://postgresql.1045698.n5.nabble.com/PgAmin3-Anonymous-code-block-can-t-be-executed-by-pressing-quot-Execute-PG-script-quot-button-td5771073.html

do 语句的文档在这里:

http://www.postgresql.org/docs/9.3/static/sql-do.html

于 2014-01-17T11:02:55.970 回答
5

只是为了改写和“具体化”其他人所说的话:PostgreSQL 中没有内联过程。也没有 PRINT 语句。你必须:

CREATE OR REPLACE FUNCTION test() RETURNS void AS $$
DECLARE
  num INTEGER;

BEGIN

  num := 3;
  RAISE NOTICE '%', num;

END;
$$ LANGUAGE plpgsql;

SELECT test();
于 2009-12-14T11:50:37.843 回答
3

If you're trying to print out num (say, for debugging), you could try:

RAISE NOTICE '%', num;

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

PRINT doesn't mean anything in PL/pgSQL.

于 2009-12-14T05:57:02.243 回答
1

Postgres 本身不支持类似的东西()。psql(官方命令行客户端)有一些基本的脚本。

对您来说最好的选择是 pgAdmin,它已经内置了脚本。

于 2009-12-14T10:29:16.523 回答
1

我不知道你想达到什么目的。PostgreSQL 不支持这种语法。类似的关键字(除了 PRINT?!)在 PL/pgSQL 中,它是用于构建 FUNCTIONS 的过程语言,而不是用于编写独立的 SQL 查询。

于 2009-12-14T07:33:43.380 回答