tags:

views:

69

answers:

2

I try to declare a variable in a code like this, but it's doesn't work. Can you tell me what's the problem? ERROR: syntax error at or near "VARCHAR" LINE 2: p_country VARCHAR;

DECLARE p_country VARCHAR; p_country : = ''; SELECT p_country;

A: 

Within a PL/pgSQL function you can declare variables like this:

CREATE FUNCTION identifier (arguments) RETURNS type AS '
  DECLARE

     -- Declare an integer.
    subject_id INTEGER;

     -- Declare a variable length character.
    book_title VARCHAR(10);

      -- Declare a floating point number.
    book_price FLOAT;

  BEGIN
    statements
  END;
' LANGUAGE 'plpgsql';

Source: http://www.commandprompt.com/ppbook/x19832

WoLpH
But I want to declare a variable out of the function. Is it possible?
[Not yet](http://developer.postgresql.org/pgdocs/postgres/sql-do.html)
Milen A. Radev
+1  A: 

Create a new setting in postgresql.conf for custom_variable_classes:

custom_variable_classes = 'var'

Reload the config, you now have the variabele "var" available in all your databases.

To create the variable p_country, just use SET:

SET var.p_country = 'US';
SELECT current_setting('var.p_country') AS p_country;

It's not a beauty, but it works.

Frank Heikens
It's interesting. But the poblem is that I make queries to the remote server. I don't think I'll be allowed to edit postgresql.conf.
You could ask them to add this in the configuration, it aint rocket science. You could also use a temp table to put your variables in.
Frank Heikens