0

I'm trying to compile a postgresql function

CREATE OR REPLACE FUNCTION LoadData(tablename varchar(25), filepath varchar(35))
RETURNS void AS $$
declare

BEGIN

RAISE NOTICE 'Data is being loaded from an external file, please wait...';

COPY tablename FROM filepath DELIMITER ',' CSV HEADER;


RAISE NOTICE 'Data loaded successfully!!';
END;
$$ LANGUAGE plpgsql;

but it's giving an error like this

ERROR:  syntax error at or near "filepath"
LINE 9: COPY tablename FROM filepath DELIMITER ',' CSV HEADER;

How to use both the in parameters in the COPY command?

0

1 Answer 1

1

To execute dynamically built SQL queries use execute. format makes it easy and safe

create or replace function loaddata(
    tablename varchar(25), filepath varchar(35)
) returns void as $$
begin

raise notice 'data is being loaded from an external file, please wait...';

execute format($copy$
    copy %I from %L delimiter ',' csv header
    $copy$,
    tablename, filepath
);

raise notice 'data loaded successfully!!';
end;
$$ language plpgsql;

http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.