You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ADO.NET在.NET 4中获取Oracle PL/SQL函数返回的0/1结果?

解决.NET 4调用Oracle函数获取返回值的问题

问题根源

你的代码存在几个关键问题:

  1. PL/SQL块里变量名写错:声明的是Wresult,赋值时却写成了w,导致函数返回值没正确存到变量里
  2. 未将函数结果绑定到输出参数,即使添加了输出参数也无法传递值
  3. ExecuteNonQuery用于执行增删改语句,返回受影响行数,对PL/SQL块默认返回-1,不能用它获取函数结果

解决方案一:用输出参数传递结果

修正PL/SQL块,将函数结果赋值给输出参数,再在C#中读取:

  1. 修正SQL语句:
string str1 = "declare Wresult number;" +
              "begin " +
              "Wresult := tis.fuc(:pre1, :pre2, :pre3, :pre4, :pre5);" +
              ":out_result := Wresult;" +
              "end;";
  1. 完整C#代码:
using (OracleConnection connection = new OracleConnection(OracleServer))
{
    connection.Open();
    using (OracleCommand command = new OracleCommand(str1, connection))
    {
        command.CommandType = CommandType.Text;

        // 添加输入参数
        command.Parameters.Add("pre1", OracleDbType.Int32).Value = 1;
        command.Parameters.Add("pre2", OracleDbType.Int32).Value = in1;
        command.Parameters.Add("pre3", OracleDbType.Int32).Value = in2;
        command.Parameters.Add("pre4", OracleDbType.Int32).Value = in3;
        command.Parameters.Add("pre5", OracleDbType.Int32).Value = in4;

        // 添加输出参数
        command.Parameters.Add("out_result", OracleDbType.Int32, ParameterDirection.Output);

        // 执行PL/SQL块
        command.ExecuteNonQuery();

        // 获取结果
        int result = Convert.ToInt32(command.Parameters["out_result"].Value);
    }
    // using块会自动关闭连接,无需手动调用connection.Close()
}

解决方案二:直接调用函数(更简洁)

跳过PL/SQL块,直接通过select调用函数,用ExecuteScalar获取单行单列结果:

  1. 简化SQL语句:
string str1 = "select tis.fuc(:pre1, :pre2, :pre3, :pre4, :pre5) from dual;";
  1. 完整C#代码:
using (OracleConnection connection = new OracleConnection(OracleServer))
{
    connection.Open();
    using (OracleCommand command = new OracleCommand(str1, connection))
    {
        command.CommandType = CommandType.Text;

        // 添加输入参数
        command.Parameters.Add("pre1", OracleDbType.Int32).Value = 1;
        command.Parameters.Add("pre2", OracleDbType.Int32).Value = in1;
        command.Parameters.Add("pre3", OracleDbType.Int32).Value = in2;
        command.Parameters.Add("pre4", OracleDbType.Int32).Value = in3;
        command.Parameters.Add("pre5", OracleDbType.Int32).Value = in4;

        // 直接获取函数返回值
        int result = Convert.ToInt32(command.ExecuteScalar());
    }
}

注意事项

  • 确保tis.fuc的第五个参数类型匹配:原PL/SQL示例里是字符串'3311',但你的C#代码里用了OracleDbType.Int32,如果函数第五个参数是字符串类型,要改成OracleDbType.Varchar2,避免类型错误
  • using块会自动释放连接和命令资源,无需手动关闭连接

内容的提问来源于stack exchange,提问作者sp 4_4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:20:52