3

I'm trying to declare integer variable with default value 0 in postgresql sql script:

DECLARE user_id integer;

but it returns exception:

ERROR: syntax error at or near "integer"

I'm not sure how can I declare a variable and then use this variable inside while loop.

1

2 Answers 2

6

You must put your code inside a user defined function. It will not work on a sql window. Example below is a function that returns the number you send.the variable

  --mybase is your database name. If public, remove it.
  CREATE OR REPLACE FUNCTION mybase.my_new_rotine(numeric)
  RETURNS numeric AS
  $BODY$
  --here, get the first variable from function
    declare id numeric= $1;

    begin
   --return the number
       return id;
    end;
  $BODY$

  LANGUAGE plpgsql VOLATILE

An then, you can use it on a sql window, like this:

  select * from mybase.my_new_rotine(1)

will return 1

Sign up to request clarification or add additional context in comments.

Comments

5

You can't use DECLARE in a SQL statement. What you want to do requires plpgsql. danielarend's answer is right, but you might want to explore DO (https://www.postgresql.org/docs/current/static/sql-do.html) which lets you write adhoc plpgsql without the need of defining a function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.