How to fix the error of dynamically generated T-SQL query when the syntax is correct?

Problem:

I was generating a query using dynamic SQL and copied the result from grid and pasted into a query window and executed the same. This resulted in error.

This is the error I got when I copied the query from result grid and pasted into another query window and executed it.

Error message:

Msg 102, Level 15, State 1, Procedure sp_stored_proc_name_here, Line 1 [Batch Start Line 0] Incorrect syntax near 'GO'.

image.png

Solution:

When I copied the result, the CR/LF was not retained. so when I pasted the result, the entire query was in a single line without CR/LF. So the batch separator "GO" at the end of the line has caused this error.

Enabling this option in SSMS and restarting the SSMS has solved the issue.

image.png

After enabling this setting, when you copy from the result grid, the CR/LF is retained. Hence you see the pasted query in multiple line with original format.

image.png

Thanks for reading.