I want to write script in SQL that will copy these 2 tables(A,B) to other 2 tables(C,D) with the same structure as A,B accordingly.
IMPORTANT:
- Tables C,D are NOT necessary empty
- Several processes may call script simultaneously
Table A has foreign key(fk_a_b) of table B
________________________ _________________
| Table A | | Table B |
|______________________| |_______________|
| id FK_A_B name | | id visible |
| ----- -------- ------| | ----- --------|
| 1 21 n1 | | 21 true |
| 5 32 n2 | | 32 false |
------------------------ -----------------
Let say that after copying table B to D this is what I get
________________
| Table D |
|______________|
| id visible |
| ----- -------|
| 51 true |
| 52 false |
----------------
Now, when I’ll copy table A to C I need to know, somehow, that ID=21 maps now to ID=51, and ID=32 to ID=52. Finally, the table C will be:
________________________
| Table C |
|______________________|
| id FK_C_D name |
| ----- -------- ------|
| 61 51 n1 |
| 62 52 n2 |
------------------------
Because several processes may call script simultaneously, I CAN’T alter table A,B to add some helper columns. So, to achieve this I used CURSOR. I copied row by row of table B and managed temp table to map OldId to NewId(21->51,32->52) and then used this temp table to copy table A.
I’ve read that CURSOR is bad practice. So, is there another way to do it?
Thank you
You can use the output clause with the merge statement to get a mapping between source id and target id.
Described in this question. Using merge..output to get mapping between source.id and target.id
Here is some code that you can test. I use table variables instead of real tables.
Setup sample data:
Copy data:
Result:
You can test the code here: https://data.stackexchange.com/stackoverflow/q/101643/using-merge-to-map-source-id-to-target-id