我正在从 C# 代码运行 SQL 脚本,我的问题是代码需要很长时间才能完成执行,它有很多表要在脚本中创建(至少 30 个表),所以我的代码可以工作但是它有性能问题。 这是代码
public static bool executeSqlScript(string scriptPath,string serverName,string databaseName)
{
try
{
SqlConnection myConn = new SqlConnection("Server=.;Integrated security=SSPI;database=master");
Server server = new Server(new ServerConnection(myConn));
string CreateCommand = "CREATE DATABASE " + databaseName + "";
string appendText;
//delete first line from script(Oldscript)
var lines = File.ReadAllLines(scriptPath).Skip(1);
File.WriteAllLines(scriptPath, lines);
using (StreamReader sreader = new StreamReader(scriptPath))
{
appendText = sreader.ReadToEnd();
}
File.Delete(scriptPath);
using (StreamWriter swriter = new StreamWriter(scriptPath, false))
{
appendText = "USE [" + databaseName + "]" + Environment.NewLine + appendText;
swriter.Write(appendText);
swriter.Close();
}
string readtext = File.ReadAllText(scriptPath);
SqlCommand myCommand = new SqlCommand(CreateCommand, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
server.ConnectionContext.ExecuteNonQuery(readtext);
return true;
}
catch (Exception e)
{
throw e;
return false;
}
}
最佳答案
我的建议是将其中的大部分迁移到 SQL Server,一旦设置了新的数据库和用户,调用存储过程来读取其中包含必要 DDL 的 SQL 文件。
我的上一个项目是一家托管公司,我们的 CMS 使用了 150 多个数据库对象。我们使用了一个“控制”数据库,我们将新的数据库信息传递给它,它通常会在不到一分钟的时间内创建新的表、函数和过程。
关于c# - 从 ASP.Net C# 应用程序性能问题运行 SQL 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826341/