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?