1

I have a parent and child table, I need to move column information from the parent column to the respective child column.

CREATE TABLE public.parent
(
  id character varying(255) NOT NULL,
  name character varying(255),
  surname character varying(255),
  CONSTRAINT parent_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.parent
  OWNER TO postgres;

CREATE TABLE public.child
(
  id character varying(255) NOT NULL,
  childname character varying(255),
  parentid character varying(255),
  surname character varying(255),
  CONSTRAINT child_pkey PRIMARY KEY (id),
  CONSTRAINT child_parentid_fkey FOREIGN KEY (parentid)
      REFERENCES public.parent (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.child
  OWNER TO postgres;

I have a surname column in parent table, I need to move that data to the respective child.

what I've done so far,

DO $$
DECLARE 
   t_curs cursor for 
      select * from parent;
BEGIN
    FOR t_row in t_curs LOOP
    RAISE NOTICE '%', t_row;
        update child set surname = (select surname from parent where id =  t_row.id) ;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

But with the above example, the last parent surname in the iteration is being updated to all the child tuples.

Is there another approach to do this?

3
  • 2
    You don't need a loop or PL/pgSQL for this Commented Jan 14, 2020 at 15:22
  • @Shiva any luck? Commented Jan 15, 2020 at 22:47
  • Yeah. that works. I have made it complicated unnecessarily. Commented Jan 20, 2020 at 12:27

1 Answer 1

4

Do you really need a PL/pgSQL for this? I believe a simple UPDATE would suffice:

UPDATE public.child
  SET surname = p.surname
FROM public.parent p
WHERE parentid = p.id;
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.