Thursday, November 01, 2007

Making the world safe for .NET SQLCommand, SQL Scripts and the "Go" Statement

.NET Playground - SQL Server GO statements

"Why don't go statements work within a SQL script I run from my .net program?

This is simply because "go" isn't SQL. It's only able to be interpreted by management studio, so when you run it from your application, it's going to throw you errors saying it's invalid SQL (and rightfully so).

...

But there is a simple way around this.

The first thing you need to do is do a replace-all in your Sql Script. Open your script up and replace "go" with "go--runtoline". Make sure you have 'match whole word' on, otherwise you'll mess up a heap of stuff. When you run the script it should run exactly the same as before you did the replace.

Next thing is in your code, you want to split up the script into a set of sub routines as such:

..."

Now that's a cool idea...

This keeps the original SQL Script in a form that can be executed from Query Analyzer/SQL Management Studio, as well as via .Net SQLCommand.

I think I like this approach in that it seems to give more control over the process...
(Think a long script, filled with many different statements broken into Go blocks and then getting an error in the middle somewhere... )

 

Related Past Post XRef:
Execute T-SQL Scripts (with GO's) Programmatically with SMO (or DMO)
Call SQLCMD from .Net with Output Capture

2 comments:

Anonymous said...

I don't understand why you need to replace "go" with "go--runtoline". Why not simply change the .NET code to split with a different regex (eg "^\s*GO\s*--.*?$") and leave the original script untouched?

Regards,

Greg said...

I don't regex enough to be comfortable with it, but using it does seem to make sense.

Doing a search and replace on the SQL Script might make it a little more deterministic, certain, (i.e. less magic) and makes it clear exactly where the .Net code will break the script into sub batches...

But I agree not having to edit the SQL script beforehand has a great deal of appeal.

Thanks for pointing it out...