how to declare variable in PostgreSQL

后端 未结 2 1042
春和景丽
春和景丽 2020-12-21 13:12

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\"
LI         


        
相关标签:
2条回答
  • 2020-12-21 13:47

    Create a new setting in postgresql.conf for custom_variable_classes:

    custom_variable_classes = 'var'
    

    Reload the config, you now have the variable "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.

    0 讨论(0)
  • 2020-12-21 13:51

    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

    0 讨论(0)
提交回复
热议问题