Most likely you are getting your single quote occurances incorrect. ie. to place a literal single quote in a string you have to ...

'beforequote''afterquote'

... and to nest another level inside that you have to ..

'beforenestedstring''insidenestedstring''''stillinside''notinnestedstring'

This is really because you are writing a SQL to generate a series of SQL's that then generate another series of SQL's -- the example i gave just "jumps" straight down to the lowest level in one go.