I’ve unique rows with primary key in my emp table.
select * from EMP E;
Now I’ve created emp_backup table which takes backup of emp table like.
insert into emp_backup
select * from emp e
where not exists (select EMPNO from emp_backup E1 where E1.EMPNO=e.EMPNO);
the above query successfully copies all the rows from emp to emp_backup and it make sure when you again run above query it will not copy the existing rows from emp to emp_backup table in next run.
now my problem is when i update any record in emp table and try to run above query it gives me error of primary key violation which is excepted.
for example.
update EMP
set JOB='worker'
where EMPNO=14;
I update emp table after copying the record with empno 14 to emp_backup table.
when i run insert into emp_backup.... query i want this update change should refelect into emp_backup table.
How can i modify the above query so that it will copy the updated rows with existing primary key from emp to emp_backup.
I hope my question is clear, tell me how i can improve it.
It seems that when you created your emp_backup table, that you also created a table PK on the EMPNO table. This will prevent you from inserting the same emp record twice.
You need to rethink your ‘backup’ plan – do you want
For 1:
emp_backup_id int identity(1,1), and possibly a newCURRENT_TIMESTAMPdefaulted column to assist you in determining which is the latestAfter dropping your PK, updated records can be ‘backed up’ as:
(Note that columns of certain types can’t be compared directly)
For 2, you would need to update existing records in your emp_bak table:
But your table mirroring begs the question, everytime you want a backup, why not just drop your existing emp_backup table and do:
??