c# - 如何在C#上查看存储过程更新结果

标签 c# stored-procedures

查看我继承的一些源代码,有一段代码调用 SQL 存储过程进行更新。

如果出现问题,存储过程返回 -1:

IF @@Error <> 0
    BEGIN
        ROLLBACK TRAN
        SELECT -1
        RETURN
    END
COMMIT TRAN
SELECT 0

C#代码是这样的:

    System.Data.SqlClient.SqlDataReader myReader;
    try{
        SqlDbConnection.Open();
        SqlDbCommand.Connection = SqlDbConnection;
        SqlDbCommand.CommandType = System.Data.CommandType.StoredProcedure;
        SqlDbCommand.CommandText = "StoredProcedured_UpdateFoo";
        SqlDbCommand.Parameters.Clear();
        SqlDbCommand.Parameters.Add("@FooData", SqlDbType.DateTime); SqlDbCommand.Parameters["@FooData"].Value = System.DateTime.Now.ToString("yyyy-MM-dd");
        myReader = SqlDbCommand.ExecuteReader();   
        if (myReader.Read())
           {
             if (int.Parse(myReader.GetValue(0).ToString()) == -1) throw new ErrorDataTxRx("Error FOO ");
           }
    } finally {
      if (SqlDbConnection.State != ConnectionState.Closed){
           SqlDbConnection.Close();
      }

      if (myReader != null){              
          if (!myReader.IsClosed) myReader.Close();
      }
    }

我也看到了相同代码的一部分,使用 System.Data.DataSet() 和 Fill 方法检查相同的内容。
有没有更优雅的方法来检查返回值是否为-1?
在这种情况下可以使用 ExecuteReader 吗?

最佳答案

您是否尝试过使用 ExecuteScalar ?这是为返回单个值的查询设计的:

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored

关于c# - 如何在C#上查看存储过程更新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759660/

相关文章:

c# - 从 C# 设置/运行 PostgreSQL

c# - 使用进度条时出现"Operation already completed"错误

mysql - 想要在以下程序中应用交易,但它不起作用

c# - .net core 和 .net framework 4.6 的 Nuget 包兼容性

c# - ModelMetaData、Custom Class Attributes 和一个难以描述的问题

c# - 将带有颜色名称的字符串转换为颜色“id”

tsql - 为什么我的类型化数据集不像临时表?

mysql - 如何停止执行MySQL中的完整存储过程?

mysql - 无法创建此存储过程。它有什么问题

Mysql 触发器或存储过程在更新同一表中的 B 列时更新 A 列