3

I want my stored procedure to allow user to update the data.

Here's the procedure :

CREATE OR REPLACE FUNCTION update_table (
   IN _table      character varying,
   IN _col_mod    character varying,
   IN _val_mod    character varying,
   IN _col_filter character varying,
   IN _val_filter character varying
)
RETURNS void
AS
$$
BEGIN
    RAISE NOTICE 'Update table %', _table;
    EXECUTE ' UPDATE ' || quote_ident(_table) || ' SET ' || quote_ident(_col_mod) || ' = $1 WHERE ' || quote_ident(_col_filter) || ' = $2'
    USING _val_mod, _val_filter;
END;
$$
LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER; 

I wanna ask, is this procedure is efficient? because it looks like I just recreate the query.

And the reason why I create a procedure like this is in my office I had new policy that DBA not allowed to perform query directly into database. We must use stored procedure to do the DML also data retrieval query.

Thanks in advance .. :D

2
  • 1
    The overhead of calling one procedure to construct a string isn't huge. Executing a command in this way shouldn't add much overhead. I presume the purpose of the new office policy is to protect the production database by making sure that everything executed against it can be checked. With this in mind, your procedure does appear to be in breach of this policy as you're basically passing in half the command as arguments. Commented Mar 5, 2012 at 9:58
  • This is weird, if this is what the policy requires you to do it's maybe better to send your SQL in an e-mail to whoever is allowed to query the database. Commented Mar 5, 2012 at 22:17

1 Answer 1

3

If it is 9.1 you can use format() to make it more legible:

EXECUTE format(
    'UPDATE %I SET %I = $1 WHERE %I = $2', _table, _col_mod, _col_filter
    )
USING _val_mod, _val_filter;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.