How to declare variable and assign value into that in postgresql? - 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

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

I tried to do this as an edit, but the edit was rejected as being too small.
The problem you're running into is a misunderstanding of plpgsql's (somewhat confusing) block syntax. If you look on that page, the critical part you're missing is this:
[ DECLARE
declarations ]
There can be multiple declarations in a single DECLARE section. You can also nest blocks:
DECLARE
c_pi CONSTANT double precision := pi();
v_text text;
BEGIN
DECLARE
v_blah text;
BEGIN
NULL;
END;
END;
Note that the semicolon is optional on the outer-most block.

Related

string array as parameter to plpgsql procedure

Can some one guide me how to test this procedure. (code got compiled but dont know if it is correct or not).
CREATE OR REPLACE PROCEDURE create_update_h( p_a_pkg_array CHARACTER VARYING [],p_u_pkg_array CHARACTER VARYING [] , inout out_error_code TEXT , inout out_error_text text )
LANGUAGE 'plpgsql'
calling with
do
$$
DECLARE out_error_code TEXT;
DECLARE out_error_text TEXT;
BEGIN
CALL create_update_h(
['t','t','t']::CHARACTER VARYING [],[result1,result2,result3]::CHARACTER VARYING [],out_error_code::TEXT,out_error_text::TEXT);
RAISE NOTICE 'myvar1 = %', out_error_code;
RAISE NOTICE 'mymsg1 = %', out_error_text;
END;
$$
giving error
ERROR: syntax error at or near "["
LINE 9: [t,t,t]::CHARACTER VARYING [],[result1,result2,result3]::CH...
^
SQL state: 42601
Character: 162
I tried the above script to test the proc . Could somebody tell me how to call a proceudre that has 2 arrays as input.
The syntax for array constructor in PostgreSQL is:
ARRAY[field, field ...]
The keyword ARRAY is mandatory

PostgreSQL using NO_DATA_FOUND exception in a sored Procedure

When I try to run a PostgreSQL stored procedure including the "STRICT" option and a record variable (rec) as I try to save (run the create statement) I get the following error:
ERROR: syntax error at or near "rec"
LINE 14: INTO STRICT rec
I' am following the guidelines stated on the official documentation https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW
where the only reference missing is that this can or can't be used inside a function or a stored procedure. I guess there should be a reasonable answer to this issue I couldn't found. I was able to succeed running an equivalent code inside a Do block, so it seams there is some incompatibility declaring a record type variable and functions.
This is the function code I was running:
CREATE OR REPLACE FUNCTION test_nodata()
RETURNS TABLE(id int, active boolean)
LANGUAGE plpgsql
AS $$
DECLARE
rec record;
tab VARCHAR ='text_maintenance_news';
BEGIN
RETURN QUERY
SELECT tm.id, tm.active
INTO STRICT rec
FROM text_maintenance_news tm
WHERE tm.active
LIMIT 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE 'Query from % has no data', tab;
END;
$$
As mentioned at the official documents, postgreSQL doesn't consider no data as an error but as a warning that the programmer must handle. Main reason to include the STRICT option.
Do block code (It works!) and result:
DO
LANGUAGE plpgsql
$$
DECLARE
rec record;
tab varchar = 'text_maintenance_news';
BEGIN
SELECT *
INTO STRICT rec
FROM text_maintenance_news
WHERE active
LIMIT 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE 'Query from % return no data', tab;
END;
$$
ERROR: Query from text_maintenance_news return no data
CONTEXT: PL/pgSQL function inline_code_block line 13 at RAISE
SQL state: P0001

How to concat two string in postgresql function?

I want a function which will return concated string. I am getting following error after execute this function in postgresql.
CREATE OR REPLACE FUNCTION getTableName ()
RETURNS text AS $$
DECLARE
state_short_name text;
BEGIN
state_short_name := (select lower(state_short_name) from mst_state where state_code in (SELECT substr(entity_code,1,2) FROM shg_detail_share WHERE entity_code = '3420006002001'))
RETURN (CONCAT(state_short_name, '_shg_detail'));
END;
$$ LANGUAGE plpgsql
I expect the output like 'jh_shg_detail' but I am getting error like this
ERROR: syntax error at or near "("
LINE 9: RETURN (CONCAT(state_short_name, '_shg_detail'));
You should use a select into in PL/pgSQL. And to avoid a name clash, don't name variables the same as columns:
CREATE OR REPLACE FUNCTION gettablename()
RETURNS text AS $$
DECLARE
l_state_short_name text;
BEGIN
select lower(state_short_name)
into l_state_short_name
from mst_state
where state_code in (SELECT substr(entity_code,1,2)
FROM shg_detail_share
WHERE entity_code = '3420006002001'));
RETURN CONCAT(state_short_name, '_shg_detail');
END;
$$ LANGUAGE plpgsql;
But you don't need PL/pgSQL for a simple SQL query like that. Your sub-query isn't really necessary as well. You can simplify that to where state_code = '34'
CREATE OR REPLACE FUNCTION gettablename()
RETURNS text
AS $$
select concat(lower(state_short_name), '_shg_detail')
from mst_state
where state_code = '34';
$$
LANGUAGE sql;
Your problem is a missing semicolon at the line with the assignment statement :=.
This makes the line that starts with RETURN (CONCAT a continuation line of the statement, and so you get the syntax error reported in that line.

syntax error when running postgresql function/stored procedure

Trying to perform a set of complex Postgresql DB operations by using function, but even a simple function gets me error:
ERROR: syntax error at or near "text"
LINE 3: tmp text := info;
^
Here is SQL
CREATE or REPLACE FUNCTION createme (info text) RETURNS text AS $$
DECLARE
tmp text := info;
BEGIN
select :tmp
end
$$ LANGUAGE SQL;
Any idea why? Thx!
You procedure is not in SQL language, but it is in plpgsql language.
CREATE or REPLACE FUNCTION createme (info text) RETURNS text AS $$
DECLARE
tmp text := info;
BEGIN
RETURN tmp;
end
$$ LANGUAGE plpgsql;
SELECT :tmp is nonsense in this content. Functions returns a value with command RETURN - it is similar to any other environments.

Postgres - ERROR: syntax error at or near "IF"

I have a function and I need to do different select based on inputid. so I have added the condition as below.
....
begin
IF(iv_binrocess = 1 AND IsNull(iv_binno,'') != '') THEN
...//some process here
END If;
...
End
When I run the function, I got the error "
ERROR: syntax error at or near "IF"
I referred many sites and tutorials, nothing helped me.
Can anyone help me to fix this issue?
Thanks
WAG, since you deleted most of the important information: You're trying to create a function with a PL/pgsql body, but declaring it SQL.
craig=> CREATE FUNCTION test() RETURNS void LANGUAGE sql AS
$$ BEGIN IF TRUE THEN PERFORM 1; END IF; END; $$ ;
ERROR: syntax error at or near "IF"
LINE 1: ...TION test() RETURNS void LANGUAGE sql AS $$ BEGIN IF TRUE TH...
Declare PL/PgSQL functions as LANGUAGE plpgsql.
If you instead want to use an SQL function, use a CASE expression instead of IF.
CREATE FUNCTION test2() RETURNS integer LANGUAGE sql
AS $$ SELECT CASE WHEN TRUE THEN 1 ELSE 0 END; $$;
(Note, I haven't bothered to format these readably. Don't write functions all in one line like this in real code.)