我正在执行一个SQL插入语句,例如
INSERT INTO Table (fk1, value1) OUTPUT inserted.pk VALUES ('fkv1', 'v1');
其中“pk”是自动递增的键值,如:
SqlDataReader reader = cmd.ExecuteReader();
外键与父表冲突,而reader.HasRows()反映了这一点,但是如何检索与错误描述一起抛出的实际异常对象?如果删除“OUTPUT”语句,它会抛出异常,但是在那里使用该语句,它会吞下错误,然后返回“HasRows”== false。
我可以在“结果视图”属性下使用调试器看到错误,但是如何在代码中获取此值?
Sql Server 2008r2 .NET 4.0
感谢您的帮助。
编辑:
此调用不会引发异常。它没有成功完成的唯一迹象是“HasRows”是错误的。
答案 0 :(得分:3)
try
{
SqlDataReader reader = cmd.ExecuteReader();
}
catch(Exception ex)
{
string errorMessage = String.Format(CultureInfo.CurrentCulture,
"Exception Type: {0}, Message: {1}{2}",
ex.GetType(),
ex.Message,
ex.InnerException == null ? String.Empty :
String.Format(CultureInfo.CurrentCulture,
" InnerException Type: {0}, Message: {1}",
ex.InnerException.GetType(),
ex.InnerException.Message));
System.Diagnostics.Debug.WriteLine(errorMessage);
}
答案 1 :(得分:0)
我有一块sql正在生成一个异常但是try catch没有捕获它 - 它太奇怪了!
这是代码
try
{
// Run the SQL statement, and then get the returned rows to the DataReader.
SqlDataReader MyDataReader = MyCommand.ExecuteReader();
//note AT THIS POINT there is an exception in MyDataReader
//if I view MyDataReader in Watch I see this in base->ResultsView->base
//Conversion failed when converting the varchar value 'lwang' to data type int
//and errors count is 1 but there is no exception catch!!
int iRow = 0;
if (MyDataReader.HasRows)
{
int iCol = 0;
while (MyDataReader.Read())
{
//dt.Load(MyDataReader);
List<String> strFields = new List<String>();
for (int iField = 0; iField < MyDataReader.FieldCount; iField++)
{
strReturn = strReturn + MyDataReader[iField] + ",";
strFields.Add(MyDataReader[iField].ToString());
}
DataRows.Add(strFields);
iRow++;
}
}
}
catch (Exception ex)
{
//no exception is caught in this case!! This code is never reached!!
strError = "An error occurred getting the data table: " + MyCommand.CommandText + " " + ex.ToString();
throw new Exception(strError);
return (DataRows);
}
finally
{
Connection.Close();
}
return (DataRows);
}
如果它有帮助,那么正在执行的sql 正在执行的sql是:
选择 hec_recommendation.RecID,hec_recommendation.UtilityID,hec_recommendation.CatID,hec_recommendation.Condition,hec_recommendation.RecommendationText,hec_recommendation.Active,hec_recommendation.Ordinal,hec_recommendation.StartDate,hec_recommendation.EndDate,hec_recommendation.CreateDate,hec_recommendation.CreatedByID,hec_recommendation.ModifyDate,hec_recommendation。 ModifyByID 来自hec_recommendation,hec_utility,hec_reccategory在哪里 hec_recommendation.utilityid = hec_utility.id和 hec_recommendation.catid = hec_reccategory.catid和 hec_reccategory.utilityid = hec_utility.utilityid和 hec_utility.utilityId ='lwang'