0

我正在使用带有 RAISERROR 的存储过程。SP 引发的错误不会被 c#.Net 中的 try catch 语句捕获。我使用 SqlDataSource 进行 SQL 连接和 SqlDataSource_Updating 事件来更新数据。

SQL 代码:

DECLARE @count int
@count=0
   if(@count = 0)
   begin
   RAISERROR('Updation failed. record already exists', 16, 1) 
  end

c#代码:

protected void sqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
  try
  {
    // Assigns the update command parameter
    e.Command.Parameters.Add(new SqlParameter("@fag", Flg));
    e.Command.Parameters.Add(new SqlParameter("@Date", DateTime.Now));

  }
  //catch (SqlException ex)
  //{


  //}
  catch (Exception ex)
  {
    // If so, checks the Exception message
    if (ex.Message == "Updation failed. record Not exists")
    {
        // Display the details of the exception to the user
        lblMessage.Text = " record already exists";
    }

    // Writes the error in log file
    WriteErrorLog(ex.Message , "sqlDataSource_Updating");
  }
}

SQL 数据源:

                SelectCommand="SELECT [ID], [Name], [Flg] FROM [Master] ORDER BY Name "  

                InsertCommand="exec [Master_Insert] @ID, @Name, @Flg, @createdDate, @createdBy, @updatedDate, @updatedBy"

                UpdateCommand="exec [Master_Update] @ID, @Name, @Flg, @updatedDate, @updatedBy"

                 DeleteCommand="DELETE FROM Master WHERE ID = @ID" 
                            oninserted="sqlDataSource_Inserted" 
                            oninserting="sqlDataSource_Inserting" 
                            onupdated="sqlDataSource_Updated" 
                            onupdating="sqlDataSource_Updating"> 
                </asp:sqldatasource>

问候 Geetha

4

3 回答 3

1

Updating事件用于自定义正在执行的SqlCommand,但它不执行该命令。try/catch 块必须包装命令执行的实际位置,而不是自定义回调。

于 2009-11-11T19:07:24.323 回答
0

我立即注意到的一件事是您的存储过程引发的错误消息“更新失败。记录已存在”与文本字符串“更新失败。记录不存在”不匹配,您正在检查您的 try/catch堵塞。

于 2009-11-11T12:20:33.123 回答
0

感谢您的所有回复。

通过在 sqlDataSource_Updated 中使用 e.Exception,我的问题得到了解决。

protected void sqlDataSource_Updated(object sender, SqlDataSourceStatusEventArgs e)

{

       if (e.Exception != null)
            {

                // If so, checks the Exception message

                if (e.Exception.Message == "record already exists")

                {

                }
         }
}
于 2009-11-12T11:41:13.383 回答