Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I want to know whether in c#.net there is any way to execute a .sql file consisting of multiple insert and update statements separated with keyword GO without needing to add microsoft.sqlserver.management.smo. Need this alternative approach because I am getting some version issues when using microsoft.sqlserver.management.smo dll in SQL2k8 R2. I am trying to build an app that should run on any version higher than or equal to SQL 2005 db
Thanks
Posted

1 solution

You could just use a SqlCommand to execute your sql-query:

C#
var con = new SqlConnection("connstring");
var cmd = new SqlCommand("query", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();


If you have a query with one or more GO statements you will have to split the script to separate all queries and execute them one by one

C#
var fileContent = File.ReadAllText("query.sql");
var sqlqueries = fileContent.Split(new[] {" GO "}, StringSplitOptions.RemoveEmptyEntries);

var con = new SqlConnection("connstring");
var cmd = new SqlCommand("query", con);
con.Open();
foreach (var query in sqlqueries)
{
    cmd.CommandText = query;
    cmd.ExecuteNonQuery();
}
con.Close();


Probably a good idea to do this in a transaction. Depending on what kind of sql you are executing.
 
Share this answer
 
v2
Comments
AmyNeedsHelp 26-Apr-13 7:47am    
Can we use this SqlCommand to execute multiple sql quesries. I believe we can execute only one query statement using this method. I need to execute multiple sql query statements seperated with 'GO' keyword from a file
StianSandberg 26-Apr-13 8:00am    
updatead my solution :)
AmyNeedsHelp 3-May-13 8:14am    
Hey thanks, it worked!
Member 13070927 11-Apr-19 9:11am    
Thanks, it helped me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900