@MikeFal could you package it as a stored proc? Then put it in master, prefix it sp_, apply some voodoo and you can execute in the calling DB's context.
@MikeFal IIRC the batch passed to sp_executesql allows the USE statement. What if you call mydb..sp_executesql ..., would that give the required context?
@billinkc It would be an honour for me. It's just that I wouldn't like the heapers to have nightmares about purple triangles and diamonds in a most unexpected set-up.