BAQ incorrect syntax near 'FOR'

Thanks Mark,

I want to achieve something similar as explained in the post: