execute sql script c# code

public void Execute(string sqlfilePath)
{
string dbConnectionString = “”;
try
{
using (StreamReader file = new StreamReader(filePath))
using (SqlConnection conn = new SqlConnection(dbConnectionString))
{
StringBuilder sql = new StringBuilder();

string line;
while ((line = file.ReadLine()) != null)
{
// replace GO with semi-colon
if (line == “GO”)
sql.Append(“;”);
// remove inline comments
else if (line.IndexOf(“–“) > -1)
sql.AppendFormat(” {0} “, line.Split(new string[] { “–” }, StringSplitOptions.None)[0]);
// just the line as it is
else
sql.AppendFormat(” {0} “, line);
}
conn.Open();

SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
cmd.ExecuteNonQuery();

console.writeline(“Succsess”)
}
}
catch (Exception ex)
{
throw ex;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s