Michael J. Swart

December 23, 2010

Does sp_executesql Handle Batch Separators (i.e. GO)?

Filed under: SQLServerPedia Syndication,Technical Articles — Michael J. Swart @ 2:47 pm

The answer is no, but I saw something interesting when I was finding out (sometimes a one minute experiment is more effective than looking up behavior on books online).

I ran the following:

exec sp_executesql N'select 1
go
select 2
go'

Now, before reading further try to guess what the results are (or the error message).

I was surprised with the these results:

/*
go
-----------
1
 
go
-----------
2
*/

Which was unexpected. The query worked! But it treated the “go” keywords as column aliases. Of course if you were to do any one of the following:

  • Redefine your batch separator.
  • Use semicolons after the select statements
  • Add column aliases to these queries

Then you do get the expected error:

/*
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'go'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'go'.
*/

So sp_executesql does not handle batch separators (i.e. GO).

Powered by WordPress