Order by dynamic

The error is due to @result not being defined in, or passed into, the second dynamic sql string.

I cannot make out what you are trying to do but suspect you do not really want to start defining table types.