0

I am trying to convert my MySQL procedure to pgSQL function that uses rollback and commit. When I did I am getting an error like below,

ERROR: cannot begin/end transactions in PL/pgSQL HINT: Use a BEGIN block with an EXCEPTION clause instead. CONTEXT: PL/pgSQL function fun_profile_update(refcursor,character varying,character varying) line 155 at SQL statement

Please help me out. Here is my function:

1
  • 1
    Not possible. The caller of the function needs to commit or rollback Commented May 18, 2016 at 13:24

1 Answer 1

1

Although begin/end transaction cannot be used in PL/pgSQL procedure, You can throw an exception and handle it.

Sample:

CREATE TABLE public.test
(
  id serial,
  description character(255)
)
WITH (
  OIDS=FALSE
);

CREATE OR REPLACE FUNCTION insert_test(IN _description text, IN _rollback boolean DEFAULT false, OUT result integer) RETURNS integer AS $$
BEGIN
  INSERT INTO public.test(description) SELECT _description;
  IF _rollback THEN
    RAISE EXCEPTION 'rollback' USING errcode = '40000'; --code for transaction_rollback
  END IF;
  result := 1;
EXCEPTION
  WHEN transaction_rollback THEN
    result := 0;
END;
$$
LANGUAGE PLPGSQL;
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.