views:

1307

answers:

6

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.

+18  A: 

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"

gbn
how can a rollback be done?
KM
SET XACT_ABORT ON clever handling, like Red Gate does.
gbn
+3  A: 

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.

cmsjr
Don't confuse transactions and batches - the go statements specify a batch of commands which may include one or more database transactions
DJ
That's an excellent point.
cmsjr
A: 

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
KM
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
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
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.
Wyatt Barnett
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
@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
Hi KM, My problem was that I needed to create an installable application that would not require the installing user to go near the database. simply specifiy a connection string and install or fail with a usefull error
Greg B
+6  A: 

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 it's own transaction. Well, actually, each call is it's 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.

Wyatt Barnett
how will you rollback changes if there is an error in one section of the script?
KM
I plan on using a single transaction accross all statements to rollback the entire process. Cheers!
Greg B
+1  A: 

Take a look also on this:
Using table just after creating it: object does not exist

Turro
Good point. Thanks
Greg B