我在寻找从更新/插入/删除/表创建中获取结果的方法时遇到了一些麻烦...
我想得到它,就像你在 SSMS(SQL Server Management Studio)消息选项卡中看到的那样(猜测该工具是 done_in_proc)。
目前,我可以获得异常,并且可以捕获在 SQL 脚本中完成的打印。
我已经尝试过 ExecuteScalar、ExecuteReader、ExecuteWithResults,但一无所获。
谢谢,
代码:
public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError err in e.Errors)
{
richTextBoxDeployCopy.AppendText("Info : "+err.Message + Environment.NewLine);
}
}
public void ExecSQLScript(string Instance, string Database, string SQLScript, string Username, string Password)
{
if (Application2Deploy == "DUMMY")
{
server = "Server";
}
else
{
server = Instance;
} string sqlConnectionString = @"User ID=" + Username + "; Password = " + Password + ";Persist Security Info=False;Initial Catalog=" + Database + ";Data Source=" + server + "\\" + Instance;
FileInfo file = new FileInfo(SQLScript);
string script = file.OpenText().ReadToEnd();
conn = new SqlConnection(sqlConnectionString);
conn.FireInfoMessageEventOnUserErrors = true;
Server SQLserver = new Server(new ServerConnection(conn));
if (checkBoxDeployCopyTestingScript.Checked)
{
richTextBoxDeployCopy.AppendText("Test: Running SQL Script......" + Environment.NewLine);
LogFile(DateTime.Now + "Test: Running SQL Script......", LogPath);
}
else
{
try
{
SQLserver.ConnectionContext.Connect();
SQLserver.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);
SQLserver.ConnectionContext.BeginTransaction();
SQLserver.ConnectionContext.ExecuteNonQuery(script);
Error = false;
}
catch (Exception SQLEx)
{
Error = true;
richTextBoxDeployCopy.AppendText("Error executing SQL Script." + Environment.NewLine);
LogFile(DateTime.Now + "Error executing SQL Script", LogPath);
richTextBoxDeployCopy.AppendText("Exception: " + SQLEx.InnerException.Message + Environment.NewLine);
LogFile(DateTime.Now + "Exception: " + SQLEx.InnerException.Message, LogPath);
try
{
SQLserver.ConnectionContext.RollBackTransaction();
}
catch (Exception ex2)
{
richTextBoxDeployCopy.AppendText("Error executing rollback." + Environment.NewLine);
richTextBoxDeployCopy.AppendText("Exception: " + ex2.Message + Environment.NewLine);
}
}
if (Error == false)
{
SQLserver.ConnectionContext.CommitTransaction();
CopyExit("End");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
else
{
CopyExit("Abort");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
}
}