I have a function in which I pass a path to a file as a parameter. Within the function, I want to COPY the data that is located at the path
CREATE OR REPLACE FUNCTION load(path varchar)
RETURNS void
LANGUAGE plpgsql
AS
$$
BEGIN
COPY foo FROM path
WITH DELIMITER ';'
CSV HEADER;
...
end;
$$
This gives a Syntax Error, pointing to path. If I hardcode the path to C:\Users...., it works.
Why is that?
copy does not work with variables. Shape and execute dynamic SQL. Here is an illustration - your example modified. I am using dollar quoting for clarity.
CREATE OR REPLACE FUNCTION load(path text) RETURNS void LANGUAGE plpgsql AS
$$
begin
execute replace(
$dynsql$
COPY foo FROM '__PATH__'
WITH DELIMITER ';'
CSV HEADER;
$dynsql$,
'__PATH__', path);
...
end;
$$
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 ;
$$;
I'm constructing a snowflake stored procedure and I'm facing difficulty in using the passed argument in the snowflake procedure.
create or replace procedure dumper(n float)
returns float
language javascript
execute as caller
as
$$
var text = "select file_name from table(information_schema.COPY_HISTORY(TABLE_NAME=> 'records', start_time=> dateadd(hours, ?, current_timestamp())));";
var statement = snowflake.createStatement({sqlText: text, binds: [n]});
var result = statement.execute();
return statement.getRowCount();
$$
;
attempting to call the above procedure
call dumper(-2);
result in the following error
JavaScript execution error: Uncaught ReferenceError: n is not defined in DUMPER at ' var statement = snowflake.createStatement({sqlText: text, binds: [n]});' position 70 stackstrace: DUMPER line: 4
I tried using the interpolation one discussed over here but that too had no success.
Any clue on how to work with passed argument.
You have to capitalize "N" in your JavaScript code:
var statement = snowflake.createStatement({sqlText: text, binds: [N]});
Variables passed into Snowflake stored procedures behave like other object names until they're inside the JavaScript. If they're not double quoted, then Snowflake implicitly capitalizes them. Remember to uppercase all parameters passed into SPs and UDFs in Snowflake. Variables defined inside the SP or UDF using JavaScript follow the normal rules for the language.
Since the regular rules apply to Snowflake identifiers as they do to variables passed into procedures and functions, you can double quote parameters if you want to use lower or mixed case variable names:
create or replace function echo_string("n" string)
returns string
language javascript
as
$$
return n; // This works because "n" is double quoted in the signature
$$;
select echo_string('Hello world.');
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 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;
...
CREATE OR REPLACE FUNCTION Test_Param_Insert_Data(p_schema_table text, p_dblinkcon text) RETURNS void AS $$
declare
rec p_schema_table;
BEGIN
....
How to use function parameter p_schema_table as composite_type_name e.g. rec public.customer.
I tested create function, but error return
ERROR: type "p_schema_table" does not exist
Why plpgsql language don't understand p_schema_table is passing function parameter, It's should treat to table name e.g public.customer
You can't declare variable, which type is passed as parameter. In such case you should declare it using RECORD type.