58

I'm building a web app that attempts to install/upgrade the database on App_Start. Part of the installation procedure is to ensure that the database has the asp.net features installed. For this I am using the System.Web.Management.SqlServices object.

My intention is to do all the database work within an SQL transaction and if any of it fails, roll back the transaction and leave the database untouched.

the SqlServices object has a method "Install" that takes a ConnectionString but not a transaction. So instead I use SqlServices.GenerateApplicationServicesScripts like so:

string script = SqlServices.GenerateApplicationServicesScripts(true, SqlFeatures.All, _connection.Database);
SqlHelper.ExecuteNonQuery(transaction, CommandType.Text, script, ...);

and then I use the SqlHelper from the Enterprise Library.

but this throws an Exception with a butt-load of errors, a few are below

Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'USE'.
Incorrect syntax near the keyword 'CREATE'.
Incorrect syntax near 'GO'.
The variable name '@cmd' has already been declared. Variable names must be unique within a query batch or stored procedure.

I'm presuming it's some issue with using the GO statement within an SQL Transaction.

How can I get this generated script to work when executed in this way.

1

8 Answers 8

67

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"

2
  • 8
    SET XACT_ABORT ON clever handling, like Red Gate does.
    – gbn
    Jun 10, 2009 at 4:19
  • 14
    The previous answer, despite it has been Accepted, looks like a bit unclear to me. So I would like to add a relevant precision : IMHO there is absolutely no problem with wrapping transactions other multiples batches. So you can perfectly put "GO" within a transaction.
    – AFract
    Mar 19, 2014 at 9:16
52

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;
GO

SET XACT_ABORT ON; -- Roll back everything if error occurs in script
GO

-- do stuff
GO

COMMIT TRANSACTION TransactionWithGos;
GO
3
  • 9
    This only works in SQL Server Management Studio and other such tools, it is not valid SQL so this does not work in C# for example.
    – pilavdzice
    Jul 17, 2012 at 20:37
  • 2
    I was assuming you would have this is a stored procedure.
    – CodeGrue
    Jul 18, 2012 at 0:30
  • NOTE: This example will NOT work because after GO SET XACT_ABORT returns to OFF
    – Mauro
    Nov 21, 2021 at 23:58
18

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.

5
  • 1
    how will you rollback changes if there is an error in one section of the script?
    – KM.
    Jun 9, 2009 at 20:38
  • I plan on using a single transaction accross all statements to rollback the entire process. Cheers!
    – Greg B
    Jun 10, 2009 at 7:35
  • 2
    The above could split sql scripts incorrectly if you have for example, comments containing the word GO (followed by a new line) etc - so use carefully. Alternatively, you can use something like the following, which is a StringReader implementation, that will read and split the SQL, and is sensitive to comments etc: github.com/DbUp/DbUp/blob/master/src/DbUp/Support/SqlServer/…
    – Darrell
    Apr 12, 2015 at 17:24
  • @Darrell -- that is certainly the case, mainly was used for dealing with SSMS generated SQL that had no comments and plenty of GO statements. Luckily the world has progressed passed that in recent years. Apr 13, 2015 at 15:03
  • This is genius! clean and fast
    – Bizhan
    Jul 18, 2017 at 14:16
5

EDIT as pointed out below I specified tran where batch was actually correct.

The issue is not that you cannot use GO within a transaction so much as GO indicates the end of a batch, and is not itself a T-SQL command. You could execute the whole script using SQLCMD, or split it on the GO's and execute each batch in turn.

1
  • 9
    Don't confuse transactions and batches - the go statements specify a batch of commands which may include one or more database transactions
    – DJ.
    Jun 9, 2009 at 18:55
5

GO is batch seperator in SQL. It means completion of one entire batch. For Example, a variable defined in one batch @ID can't be accessed after 'GO' statement. Please refer the code below for understanding

Declare @ID nvarchar(5);
set @ID = 5;
select @ID
GO
select @ID
3

Actually, you can use GO statements, when you use the Microsoft.SqlServer.Management.Smo extensions:

    var script = GetScript(databaseName);
    var conn = new SqlConnection(connectionString.ConnectionString);
    var svrConnection = new ServerConnection(conn);
    var server = new Server(svrConnection);
    server.ConnectionContext.ExecuteNonQuery(script);

http://msdn.microsoft.com/de-de/library/microsoft.sqlserver.management.smo.aspx

All you need is the SQL CLR Types and SQL Management objects packages deployed from: http://www.microsoft.com/en-us/download/details.aspx?id=29065 (SQL 2012 version)

2

test your scripts:

  • restore a production backup on a backup server
  • run run scripts with GOs

install your scripts:

  • shut down application
  • go to single user mode
  • backup database
  • run scripts with GOs, on failure restore backup
  • go back to multi user mode
  • restart application
7
  • 1
    Down vote this if you like, but you won't get multiple GOs in a single transaction. Based on the OP error, there are CREATEs in the script, which will require GOs. The only way to rollback if something goes wrong partway is this method.
    – KM.
    Jun 9, 2009 at 20:37
  • 1
    I'm not clear on why this was downvoted. It's certainly a lot of work, but it seems to hit the idea, and allow rollbacks (unlike some of the other methods...)
    – Beska
    Jun 9, 2009 at 21:28
  • 1
    Downvoted b/c it doesn't answer the OP's question--like trying to run this within the application. Also, taking apps offline is so ugly. Jun 9, 2009 at 23:00
  • 1
    To be fair, KM's solution is 100% accurate and the safest. I only use proper differential tools and proper SQL client tools. For 3rd party apps, I don't recall ever seeing OP's solution to upgrade a databases: it's always SQL scripts and batch files.
    – gbn
    Jun 10, 2009 at 7:40
  • @Wayatt Barnett said "Also, taking apps offline is so ugly.", messing up the database with a failed script that can not be rolled back, while it is up and running, "is so ugly"
    – KM.
    Jun 10, 2009 at 12:30
1

Just thought I'd add my solution here... replace the 'GO' with a separator that ExecuteNonQuery understands i.e. the ';' operator. Use this function to fix your script:

private static string FixGoDelimitedSqlScript(string script)
{
    return script.Replace("\r\nGO\r\n", "\r\n;\r\n");
}

It may not work for complex nested T-SQL with ';' operators in them, but worked for me and my script. I would have used the splitting method listed above, but I was restricted by the library I was using so I had to find another workaround. Hope this helps someone!

PS. I am aware that the ';' operator is a statement separator and the 'GO' operator is a batch separator, so any advanced scripts will probably not be fixed by this.

3
  • 1
    This does not work very well. Even simple scripts that just ALTER VIEW or something require being in their own BATCH.
    – pilavdzice
    Jul 17, 2012 at 20:35
  • We use GO to separate batches, say between drop and create, or to start new batch where we use CREATE/ALTER. removing GO will result in another error CREATE/ALTER should be the first statement in the batch
    – vinodpthmn
    Jul 11, 2013 at 9:33
  • Hi @eka thanks for the feedback. I am fully aware of the shortcomings of this solution and have stated this in my post. I'm not sure why that merits a downvote though. Jul 15, 2013 at 10:32

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.