使用C#从Oracle检索返回值

时间:2014-07-15 17:58:03

标签: c# sql oracle

我希望能够使用c#从Oracle中的函数中检索返回值。 目前,这就是我所拥有的:

对于SQL:

 FUNCTION add_resource (
     project_view BOOLEAN,
     project_id NUMBER,
     worker_id  NUMBER,
     role_id    NUMBER) RETURN NUMBER IS
     resource_id NUMBER;
 BEGIN
   INSERT INTO RESOURCE_T (WORKERID, ROLEID, PROJECTID)
   VALUES (worker_id, role_id, project_id)
   RETURNING RESOURCEID INTO resource_id;
   RETURN resource_id;
 END add_resource;

对于C#

cmdText = "DECLARE resource_id NUMBER; BEGIN resource_id := PKG_RAP.add_resource(" + projectView + "," + id + "," + record["WORKERID"] + "," + record["ROLEID"] + "); END;"; 

using (OracleCommand cmd = new OracleCommand(cmdText, conn))
    {
         OracleTransaction trans = conn.BeginTransaction();
         try
         {
          OracleParameter prm = new OracleParameter("resource_id", OracleDbType.Int32, ParameterDirection.ReturnValue);
          cmd.Parameters.Add(prm);                      
          cmd.ExecuteNonQuery();
          trans.Commit();
         }catch 
         {
          trans.Rollback();
          throw;
         }
    }

当我在数据库中测试时,查询单独工作,但是,c#无法获取resource_id的值,只能得到" null"。任何提示将不胜感激!

2 个答案:

答案 0 :(得分:1)

这样的事情不起作用吗?

cmdText = @"select PKG_RAP.add_resource(:projectView, :projectId, :workerId, :roleId) from dual";
using (var cmd = new OracleCommand(cmdText, conn))
using (cmd.Parameters.Add(":projectView", projectView))
using (cmd.Parameters.Add(":projectId", id))
using (cmd.Parameters.Add(":workerId", record["WORKERID"]))
using (cmd.Parameters.Add(":roleId", record["ROLEID"]))
using (var tx = conn.BeginTransaction()) {
    try {
        // resource ID
        var resourceId = Convert.ToInt32(cmd.ExecuteScalar());
        tx.Commit();
        return resourceId;
    } catch {
        tx.Rollback();
        throw;
    }
}

这对我来说似乎是调用PL-SQL函数返回单个值的最简单的解决方案。

ETA:我没有足够的回复评论,但是,上面的Marc意味着你不会在你正在执行的PL-SQL块中返回任何内容。

答案 1 :(得分:1)

如果您想调用一个函数(如果您想要或必须避免select ... from dual),命令文本必须与此类似:

cmdText = "BEGIN :resource_id := PKG_RAP.add_resource(" + projectView + "," + id + "," + record["WORKERID"] + "," + record["ROLEID"] + "); END;"; 

正如John Pederson已经回答的那样,所有参数都应该被定义为绑定值,e.i。

cmdText = "BEGIN :resource_id := PKG_RAP.add_resource(:projectView, :projectId, :workerId, :roleId); END;"; 

但是,我不认为在使用C#调用时可以使用布尔变量。你必须施展它,例如到" 0"和" 1"