I have two tables:
create table test1 (
oldPrimaryKey varchar(100) primary key,
someText varchar(100)
)
create table test2 (
someText varchar(100),
oldPrimaryKey varchar(100) references test1(oldPrimaryKey)
)
I need to change oldPrimaryKey
to new one so I do this:
Drop old one key:
- alter table test1 drop constraint test1_pkey;
- alter table test2 drop constraint test2_oldprimarykey_fkey;
Create new column:
- alter table test1 add column newPrimaryKey bigint;
- Populate it using sequence:
- create sequence add_id_seq start with 1 increment by 1 cache 1;
- update test1 set newPrimaryKey = nextval('add_id_seq');
- Change “newPrimaryKey” column to be primary key:
- alter table test1 add constraint keyName primary key(newPrimaryKey);
Now I have something like this:
CREATE TABLE test1
(
oldprimarykey character varying(100) NOT NULL,
sometext character varying(100),
newprimarykey bigint NOT NULL,
CONSTRAINT keyname PRIMARY KEY (newprimarykey)
)
CREATE TABLE test2
(
sometext character varying(100),
oldprimarykey character varying(100),
CONSTRAINT test2_oldprimarykey_fkey FOREIGN KEY (oldprimarykey)
REFERENCES test1 (oldprimarykey) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
I don’t know what to do now (some script?). I need to change value from table test2
column oldprimarykey
to corresponding value from table test1
column newprimarykey
.
If it is too chaotic I will try to give an example of the normal data:
Rows from table1 (oldprimarykey, sometext, newprimarykey):
- [email protected], ‘some text’, 1
- [email protected], ‘more text’, 2
Corresponding rows from table2 (sometext, oldprimarykey):
- ‘some text’, [email protected]
- ‘text text’, test2test.com
I want to change email adress from table2 to corresponding int from table1.