postgresql 如何在PostgreSQL中声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2666861/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:28:42  来源:igfitidea点击:

how to declare variable in PostgreSQL

postgresql

提问by user307880

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; 

回答by Frank Heikens

Create a new setting in postgresql.conf for custom_variable_classes:

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

custom_variable_classes = 'var'

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

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

To create the variable p_country, just use SET:

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

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

It's not a beauty, but it works.

这不是一种美丽,但它有效。

回答by Wolph

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

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

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

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