Question

I need to create a stored procedure which can take in the schema name and table name as the parameter and make an update on the same table.

CREATE OR REPLACE FUNCTION garscratch.update_table(schema_name text, table_name text ) RETURNS void as $$
DECLARE
 table TEXT;
BEGIN
execute 'update '||schema||'.'||table_name|| 'set id = substring(id from 1 for 2) where name = "test"';
END;
$$ LANGUAGE plpgsql;

When I execute the procedure above as:

select update_table(my,my_table);

I get the error:

Column "my" does not exist.

It does not treat "my" as the schema name.

Was it helpful?

Solution

  • You'd need a space between tablename and set.
  • You need sinlge quotes around the value 'test'.
    Or if it's supposed to be a column name, you don't need quotes at all.
  • You need to sanitize identifiers to avoid SQL injection.

Use instead (complete rewrite):

CREATE OR REPLACE FUNCTION garscratch.update_table(_tbl regclass)
  RETURNS void AS
$func$
BEGIN
EXECUTE 'UPDATE ' || _tbl || $$ SET id = left(id, 2) WHERE name = 'test'$$;
END
$func$ LANGUAGE plpgsql;

Call:

SELECT garscratch.update_table('myschema.my_table');

Detailed explanation:
Table name as a PostgreSQL function parameter

OTHER TIPS

It seems to me you may have problem with the table_name|| 'set id= part - specifically I think you should add a space between ' and set. Try to print what you're executing and you may found out where the problem may be.

Execute Procedure as below:

select update_table('my','my_table');

Also change line

execute 'update '||schema||'.'||table_name|| 'set id = substring(id from 1 for 2) where name = "test"';

to

execute 'update '||schema_name||'.'||table_name|| 'set id = substring(id from 1 for 2) where name = "test"';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top