如何在PostgreSQL中声明变量

时间:2010-04-19 11:11:13

标签: postgresql

我尝试在这样的代码中声明一个变量,但它不起作用。你能告诉我这是什么问题吗?

ERROR:  syntax error at or near "VARCHAR"
LINE 2:  p_country VARCHAR;


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

2 个答案:

答案 0 :(得分:5)

在postgresql.conf中为custom_variable_classes创建一个新设置:

custom_variable_classes = 'var'

重新加载配置,您现在可以在所有数据库中使用变量“var”。

要创建变量p_country,只需使用SET:

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

这不是美,但它有效。

答案 1 :(得分:2)

在PL / pgSQL函数中,您可以声明如下变量:

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';

来源:http://www.commandprompt.com/ppbook/x19832

相关问题