C# c语言中的SQL server多命令异常捕获#
我在一个命令中执行多个更新 例如:C# c语言中的SQL server多命令异常捕获#,c#,.net,sql-server,try-catch,C#,.net,Sql Server,Try Catch,我在一个命令中执行多个更新 例如: System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(); command.CommandText="executing first updateSP" +"executing second updateSP"+.....+"executing 10th updateSP" try { command.ExecuteNonQuery(); } catc
System.Data.SqlClient.SqlCommand command = new
System.Data.SqlClient.SqlCommand();
command.CommandText="executing first updateSP" +"executing second
updateSP"+.....+"executing 10th updateSP"
try
{
command.ExecuteNonQuery();
}
catch(sqlException ex)
{
ex.message;
}
若第二、第三、第四次更新得到异常,但在catch块中,我只得到一个spupdate异常。
是否有任何方法可以获取所有更新异常?您可以始终使用SQL文本命令数组,我也始终使用连接来创建命令:
string[] cmds = new string[3] { sp1_SQL, sp2_SQL, sp3_SQL };
try
{
foreach( string sql in cmds)
{
using(System.Data.SqlClient.SqlCommand command = conn.CreateCommand())
{
command.CommandText = sql;
var rtn = command.ExecuteNonQuery();
}
}
}
catch(sqlException ex)
{
ex.message;
}
此代码将在第一个异常后中止,但如果您想继续执行每个语句而不考虑异常(使我的肚子痛),请将try/catch移动到
foreach
是,按顺序执行。=)