I have the following pl/pgsql function. (Obviously, this is not the full function, it's just the minimal amount of code needed to reproduce the problem)
CREATE OR REPLACE FUNCTION test_func(infos TEXT[][])
RETURNS void AS
$$
DECLARE
info TEXT[];
type TEXT[];
name TEXT;
BEGIN
FOREACH info SLICE 1 IN ARRAY infos LOOP
RAISE NOTICE 'Stuff: %', info;
type := info[1];
name := info[2];
RAISE NOTICE 'Done with stuff';
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
When I run the function using SELECT test_func('{{something, things},{other, data}}'::TEXT[][]);, I get the following output:
NOTICE: Stuff: {something,things}
ERROR: malformed array literal: "something"
DETAIL: Array value must start with "{" or dimension information.
CONTEXT: PL/pgSQL function test_func(text[]) line 10 at assignment
I don't understand how this error is happening. When the value of info is printed, it shows {something,things}, which seems to me to be a proper array literal.
I am using PostgreSQL version 9.4.7, in case it matters.
The variable type should be text (not text[]):
CREATE OR REPLACE FUNCTION test_func(infos TEXT[][])
RETURNS void AS
$$
DECLARE
info TEXT[];
type TEXT;
name TEXT;
...
Related
I proceed to specify my question and the solution I gave to the problem, for the benefit of the community.
I was trying to perform a multi-column insert using the identifier with a function.
For which, I was getting an error, my code was the following:
CREATE OR REPLACE FUNCTION acc.asignar_periodo(ids NUMERIC[], periodo INTEGER,codigo_subdiario VARCHAR)
RETURNS void
VOLATILE
AS
$$
DECLARE
cant_registros integer:= 0;
BEGIN
cant_registros := array_length(ids,1);
FOR i IN 1..cant_registros LOOP
EXECUTE'UPDATE '||$3||' SET periodo_tributario = $2 WHERE id = ids[i]';
END LOOP;
END;
$$ LANGUAGE plpgsql;
and my query is:
SELECT acc.asignar_periodo('{2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302}'::NUMERIC[],201612,'_08');
My solution was the following:
CREATE OR REPLACE FUNCTION acc.asignar_periodo(INTEGER[],INTEGER,INTEGER) RETURNS text VOLATILE AS
$$
DECLARE
qty integer:= array_length($1,1);
respuesta varchar := null;
BEGIN
FOR i IN 1..qty LOOP
EXECUTE'UPDATE _'||$3||' SET periodo_tributario = '||$2||' WHERE id = '||$1[i];
END LOOP;
respuesta := 'Periodo '||$2||' asignado a '||qty||' comprobantes del subdiario '||$3;
RETURN respuesta;
END;
$$ LANGUAGE plpgsql;
Note the correction, since when using EXECUTE it is necessary that the arguments escape the statements
There is no to loop needed to process the array. Postgres will process the entry array at once. After all set processing is what SQL is all about. Get into the mindset that whenever you write loop, likely incorrect and much slower. (Yes there occasions where it is necessary, but very few.) So: (see demo)
create or replace function asignar_periodo(ids numeric[], periodo integer,codigo_subdiario varchar)
returns void
language plpgsql
as $$
declare
stmt constant text = 'update %I set periodo_tributario = %s where id = any (''%s'')';
torun text;
begin
--torun = format(stmt, $3, $2, $1); -- this would work but
torun = format(stmt, codigo_subdiario, periodo, ids); -- I perfer parameter names to position reference
raise notice '%', torun;
execute torun;
end ;
$$;
Do you have any opinion?
CREATE OR REPLACE FUNCTION fnc_test()
RETURNs integer
AS
$$
declare
tb_var dba_reports[];
v_serialno int := 1;
begin
SELECT array_agg(tbl) into tb_var FROM "dba_reports" tbl;
RAISE NOTICE '%', tb_var[v_serialno].report_id;
tb_var[v_serialno].report_id :=99
return 1;
end;
$$
language plpgsql;
ERROR: syntax error at or near "."
LINE 14: tb_var[v_serialno].report_id :=99
I'm kinda new into pgplsql and so far I have to create a function that loops an array that is received as a function.
The main idea of the function is to insert new records into a table that maps each id contained in the array received with a new formatted id, the format depends on the second parameter received and return the table "idsTable".
The problem is that when I try to create the function it sends me an error:
ERROR: loop variable of FOREACH must be a known variable or list of variables
LINE 38: FOREACH objectid IN ARRAY idsList LOOP
I'm not sure if I have to declare the objectid variable cause in the examples that I have seen they didn't.
So far I have this:
CREATE OR REPLACE FUNCTION createId(idsList varchar[], objectType varchar)
RETURNS TABLE(original_id varchar, new_id char) as
$$
BEGIN
IF LOWER(objectType) = 'global' THEN
FOREACH objectid IN ARRAY idsList LOOP
INSERT INTO idsTable(original_id, new_id)
VALUES(objectid, 'GID'||nextval('mapSquema.globalid')::TEXT);
END LOOP;
ELSE
FOREACH objectid IN ARRAY idsList LOOP
INSERT INTO idsTable(original_id, new_id)
VALUES(objectid, 'ORG'||nextval('mapSquema.globalid')::TEXT);
END LOOP;
END IF;
END;
$$ LANGUAGE plpgsql;
Any ideas of what could be wrong?
edit: I haven't add the part where the idsTable is returned.
Unrelated, but: you don't really need a loop for that. And you can simplify the function by only writing the INSERT once. You also forgot to return something from your function. As it is declared as returns table that is required:
CREATE OR REPLACE FUNCTION createid(idslist varchar[], objecttype varchar)
RETURNS TABLE(original_id varchar, new_id varchar) as
$$
declare
l_prefix text;
BEGIN
IF LOWER(objectType) = 'global' THEN
l_prefix := 'GID';
ELSE
l_prefix := 'ORG';
END IF;
RETURN QUERY --<< return the result of the insert
INSERT INTO idstable(original_id, new_id)
select t.x, l_prefix||nextval('mapSquema.globalid')::TEXT
from unnest(idslist) as t(x)
returning *
END;
$$ LANGUAGE plpgsql;
Is there 'concat' function in GreenPlum? I can use concat function in postgresql and it works well, but when i use it in Greenplum, I got an error.
select concat('a', 'b');
ERROR: function concat(unknown, unknown) does not exist at character 8
HINT: No function matches the given name and argument types. You may need to add explicit type casts.
LINE 1: select concat('a', 'b');
^
Is there some other functions can instead of 'concat' function in GreenPlum? And I have tried to create a function to instead of it, but got some syntax errors also.
CREATE OR REPLACE FUNCTION my_concat(VARIADIC arr VARCHAR[] ) RETURNS VARCHAR AS $$ SELECT array_to_string(arr, ''); $$ LANGUAGE SQL;
ERROR: syntax error at or near "VARCHAR" at character 51
LINE 1: CREATE OR REPLACE FUNCTION my_concat(VARIADIC arr VARCHAR[] ...
^
Anyone can help? Thanks very much!
Like most databases, Greenplum uses "||" to concatenate two strings together.
SELECT 'Green' || 'plum';
Result:
Greenplum
its a versional issue , you have use || in place where ever u using contact function.
Greenplum doesn't have the concat function yet. May be you can modify your code to use "||" instead of concat.
Well,
First I agree that you should replace your code to use the correct SQL syntax '||' for concatenation.
If you really want to create a function to emulate the concat, you could do something like:
create or replace function myschema.concat(arg1 text, arg2 text)
returns text as
$body$
declare
v_arg1 text;
v_arg2 text;
begin
v_arg1 := arg1;
v_arg2 := arg2;
return v_arg1 || v_arg2;
end
$body$
language plpgsql volatile;
Then, the query will work:
select myschema.concat('test1', 'test2');
>>test1test2
Hope you are looking for the below query.
gpadmin=# CREATE OR REPLACE FUNCTION my_concat( character varying[] ) RETURNS VARCHAR AS $$ SELECT array_to_string($1, ''); $$ LANGUAGE SQL;
gpadmin=# select my_concat(ARRAY['Green','plum']);
my_concat
Greenplum
I'm using PostgreSQL 9.1.3 and the following functions:
CREATE OR REPLACE FUNCTION cad(INOUT args text[], OUT retval int4) AS $cad$
BEGIN
retval := 0;
RAISE NOTICE 'cad: %', args;
END;
$cad$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION dodo(in_args text[]) RETURNS text[] AS $dodo$
DECLARE
_res text[];
_rv int4;
BEGIN
_res := in_args;
EXECUTE 'SELECT cad($1)' USING _res INTO _res, _rv;
RETURN _res;
END;
$dodo$ LANGUAGE plpgsql;
When I call cad directly, I get expected output:
psql$ select cad(ARRAY['Quiz']);
NOTICE: cad: {Quiz}
-[ RECORD 1 ]---
cad | ({Quiz},0)
Time: 0,319 ms
My expected result for the dodo(ARRAY['Quiz']) call is the input array without changes. But instead I receive the following error:
psql$ select dodo(ARRAY['Quiz']);
NOTICE: cad: {Quiz}CONTEXT: SQL statement "SELECT cad($1)"
PL/pgSQL function "dodo" line 8 at EXECUTE statement
ERROR: array value must start with "{" or dimension information
CONTEXT: PL/pgSQL function "dodo" line 8 at EXECUTE statement
What is wrong here?
P.S.: I have to use EXECUTE as function to call will vary, code simplified for the purpose of question.
You want something like:
EXECUTE 'SELECT * FROM cad($1)' USING _res INTO _res, _rv;
The return type isn't two columns of text[],int it's a record of (text[],int) which needs unwrapping.