Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a large SQL script (with GO commands)

Tags:

c#

sql-server

I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program.

These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately.

Is there an easier/better way?

like image 927
Blorgbeard Avatar asked Sep 02 '08 22:09

Blorgbeard


People also ask

What does go command do in SQL?

GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server.


1 Answers

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Sample code:

public static void Main()     {           string scriptDirectory = "c:\\temp\\sqltest\\";   string sqlConnectionString = "Integrated Security=SSPI;" +   "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";   DirectoryInfo di = new DirectoryInfo(scriptDirectory);   FileInfo[] rgFiles = di.GetFiles("*.sql");   foreach (FileInfo fi in rgFiles)   {         FileInfo fileInfo = new FileInfo(fi.FullName);         string script = fileInfo.OpenText().ReadToEnd();         using (SqlConnection connection = new SqlConnection(sqlConnectionString))         {             Server server = new Server(new ServerConnection(connection));             server.ConnectionContext.ExecuteNonQuery(script);         }    } } 

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

like image 180
Jon Galloway Avatar answered Sep 20 '22 15:09

Jon Galloway