Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variable and assign value into that in postgresql?

Tags:

postgresql

I'm very new in postgresql. I read many posts in this questions, but still don't get correct answer in my simple problem and keep receiving syntax error. I'm trying declare new string variable named parents_d and in the following lines trying to assign new value as well. Please help me!

CREATE OR REPLACE FUNCTION retrieve_parents(cid integer) RETURNS text AS $$ 
BEGIN
    DECLARE pd text;    
    pd:= 'function';
    RETURN concat(cid,pd);
END;
$$ LANGUAGE plpgsql;

ERROR: duplicate declaration at or near "pd" LINE 4: pd:= 'function'; ^

********** Error **********

ERROR: duplicate declaration at or near "pd" SQL state: 42601 Character: 104

like image 286
Khuyagbaatar Batsuren Avatar asked Mar 04 '16 02:03

Khuyagbaatar Batsuren


People also ask

How do I assign a variable in PostgreSQL?

Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment, and is done by using the assignment operator (:=) on the same line as the variable's declaration.

How do you assign a selected value to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.

How do you declare and assign variables?

The first time a variable is assigned a value, it is said to be initialised. The = symbol is known as the assignment operator. It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go.

How do I declare a record variable in PostgreSQL?

We can declare a record type variable by simply using a variable name followed by the record keyword. Syntax: variable_name record; We can use the dot notation (.) to access any field from the record type variable.


1 Answers

try like this

SQL Fiddle Demo

CREATE FUNCTION retrieve_parents(cid integer) RETURNS text AS $$
DECLARE pd text;    
BEGIN

    pd:= 'function';
    RETURN concat(cid,pd);

END; $$
LANGUAGE PLPGSQL
like image 180
Juan Carlos Oropeza Avatar answered Sep 19 '22 05:09

Juan Carlos Oropeza