a blog for those who code

Tuesday 1 July 2014

Run .sql script file in C#

In this post we will show you how to run .sql script file in C#. There are two ways to run .sql script file in C# i.e. run a query which is saved in a .sql file or execute a SQL generated script file.


If you want to run a query which is saved in a SQL file in your C# code, you can do it using the below code.

string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);

If you are trying to execute a SQL generated script file you have to remove all "GO". For that you have to use the following code...

string connectionString = "Your_Connection_String"
FileInfo file = new FileInfo("Your_File_Path");
string script = file.OpenText().ReadToEnd();
script = script.Replace("GO","");
SqlConnection con = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);

Please like and share the blog if you find it interesting and helpful.

Related Articles

1 comment: