I have created an empty database. I need to run script on this empty database. So far I have found code from a website:
public bool RunScript()
{
try
{
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-PCEOPRM\SQLEXPRESS;Initial Catalog=" + DbName + ";Integrated Security=True");
con.Open();
string script = File.ReadAllText(@"C:\inetpub\wwwroot\MetisTemplateDBScript\MetisEmptyDBScript.sql");
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, con))
{
command.ExecuteNonQuery();
}
}
}
con.Close();
return true;
}catch(Exception exc)
{
return false;
}
}
But when I run it, it throws some exception due to '\n','\r' or simple slashes etc. Is there some proper method of running a large script from sql file? My file also contains GO statements.
It's not a duplicate question as it has two things 1) Go command and 2) escape characters.
Thanks is advance!