Using "GO" within a transaction Using "GO" within a transaction sql-server sql-server

Using "GO" within a transaction


GO is not a SQL keyword.

It's a batch separator used by client tools (like SSMS) to break the entire script up into batches

You'll have to break up the script into batches yourself or use something like sqlcmd with "-c GO" or osql to deal with "GO"


I just want to add that if you name your transaction, you can include multiple GO sections within in and they will all roll back as a unit. Such as:

BEGIN TRANSACTION TransactionWithGos;GOSET XACT_ABORT ON; -- Roll back everything if error occurs in scriptGO-- do stuffGOCOMMIT TRANSACTION TransactionWithGos;GO


Poor man's way to fix this: split the SQL on the GO statements. Something like:

private static List<string> getCommands(string testDataSql){    string[] splitcommands = File.ReadAllText(testDataSql).Split(new string[]{"GO\r\n"}, StringSplitOptions.RemoveEmptyEntries);    List<string> commandList = new List<string>(splitcommands);    return commandList;}

[that was actually copied out of the app I am working on now. I garun-freaking-tee this code]

Then just ExecuteNonQuery() over the list. Get fancy and use transactions for bonus points.

# # # # # BONUS POINTS # # # # # #

How to handle the transaction bits really depends on operational goals. Basically you could do it two ways:

a) Wrap the entire execution in a single transaction, which would make sense if you really wanted everything to either execute or fail (better option IMHO)

b) Wrap each call to ExecuteNonQuery() in its own transaction. Well, actually, each call is its own transaction. But you could catch the exceptions and carry on to the next item. Of course, if this is typical generated DDL stuff, oftentimes the next part depends on a previous part so one part failing will probably bugger the whole pooch.