更新c#中的错误处理

本文关键字:错误 处理 更新 | 更新日期: 2023-09-27 18:16:39

我在sqlserver中有一个客户表,其中包含一个rowversion字段,我每次更新记录时都会增加它,我只需要检查

if(Customer.rowversion=@roeversion ) where customerID=@customerID

执行更新

else RAISERROR('Update cannot be executed. There is a row version conflict.', 16, 1)

所以现在必须从我的c#代码传递一个out参数并返回错误值。也-获取刚刚执行的语句的错误码。

SELECT @ErrorCode=@@ERROR

那么我应该如何将SQLSERVER更新查询的值返回到我的c#代码中,以便我可以显示消息

更新c#中的错误处理

如果您通过ado调用您的程序。. NET,那么传递给进程的SqlParameter将像这样设置:

SqlParameter P = new SqlParameter("Name of your column", SqlDbType.Int);
P.Direction = ParameterDirection.Output;
//call your sproc
int result = (int)P.Value;

编辑

由于您使用的是Linq-to-SQL,因此将此sproc添加到方法部分中应该为该sproc创建一个c#方法签名,并为您添加out参数

如果还没有,那么应该将数据库代码放在存储过程中。存储过程看起来像这样:

CREATE PROCEDURE s_my_procedure
  @RowVersion    int ,
  @CustomerID    int ,
  ... additional fields here
  @ErrorCode     INT OUTPUT
AS
  IF EXISTS(SELECT 1
              FROM Customer
             WHERE RowVersion = @RowVersion
               AND CustomerID = @CustomerID)
    BEGIN
      UPDATE Customer
         SET ...
       WHERE RowVersion = @RowVersion
         AND CustomerID = @CustomerID
      SET @ErrorCode = 0
    END 
  ELSE
    BEGIN
      SET @ErrorCode = 1234 -- Something meaningful to your app
    END

你应该尽可能避免引发错误。

然后,假设您有一个由命令执行的存储过程:
cmd.ExecuteNonQuery();
int ErrorCode = 0;
// Note that if you are not sure about your sp, you should test this for dbnull.value first
ErrorCode = Convert.ToInt32(cmd.Parameters["@ErrorCode"].Value);