I want to write a script in SQL that will copy these 2 tables (A, B) to the other 2 tables (C, D) with the same structure as A, B.
IMPORTANT :
- Tables C, D are NOT required empty
- Several processes can invoke a script at the same time.
Table A has the 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 | ------------------------ -----------------
Say that after copying table B to D, this is what I get
________________ | Table D | |______________| | id visible | | ----- -------| | 51 true | | 52 false | ----------------
Now, when I copy table A to C, I need to somehow find out that ID = 21 is now mapped to ID = 51, and ID = 32 to ID = 52. Finally, table C will look like this:
________________________ | Table C | |______________________| | id FK_C_D name | | ----- -------- ------| | 61 51 n1 | | 62 52 n2 | ------------------------
Since several processes can invoke a script at the same time, I CANNOT modify tables A, B to add some auxiliary columns. So, for this I used CURSOR. I copied row by row of table B and managed the temporary table to map OldId to NewId (21-> 51.32-> 52), and then used this temporary table to copy table A.
I read that CURSOR is bad practice. So, is there any other way to do this?
thanks
sql sql-server tsql sql-server-2008 stored-procedures
theateist
source share