It is working for the parent table but not for the child tables.Are you saying it's working? or have you got a problem?
If a problem, then you can do some tests yourself.
Set up a temporary table with data in it, sample data that you can pass through using the insert into query. You'll only need 5 or 10 records. Keep changing the contents of the records until you get it working, and then add characters back in until it breaks. You should be able to identify what is causing the problem.
I am not sure my nested loops are correct.