调用从C#返回类型的Oracle函数

时间:2012-03-23 08:48:24

标签: c# .net oracle

我正在使用c#尝试在Oracle包中调用一个返回Type的函数。

我花了最近几天研究这个,到目前为止,我遇到的建议是:

  • 使用odp.net 11g数据访问驱动程序。
  • 确保参数输出方向设置为returnvalue
  • 确保参数输出是第一个添加的参数
  • 为输出参数指定一个udttypename,它是Oracle类型 名称
  • 确保这个udttypename是大写字母(有关她的一些类似案例已由此解决)

下面是Oracle包(包称为prefs):

Type P_Details Is Record(
   var1    a.a_Type_Key%Type
  ,var2    Varchar2(1)
  ,var3    a.b%Type
  ,var4    c.Type_Key%Type
  ,var5    d.Code%Type
  ,var6    d.Product_Path%Type
  ,var7    a.Channel_Key%Type
  ,var8    a.From_Date%Type
  ,var9    a.To_Date%Type);

Type P_List Is Table Details;

Function Get(p_1   In     Number,
             p_2   In     Varchar2,
             p_3   In     Varchar2,
             p_4   In     Date,
             p_5   In Out Varchar2) Return List;

以下是用于调用Oracle包的C#代码。

using (var connection = new OracleConnection(ConnectionString))
{
    using (var command = new OracleCommand
                             {
                                 CommandType = CommandType.StoredProcedure,
                                 CommandText = "PACKAGENAME.FUNCTIONNAME",
                                 Connection = connection,
                                 BindByName = true
                             })
    {
        var output = new OracleParameter
                         {
                             UdtTypeName = "PREFS.PREFERENCE_LIST",
                             ParameterName = "p_details",
                             OracleDbType = OracleDbType.Object,
                             Direction = ParameterDirection.ReturnValue
                         };
        command.Parameters.Add(output);
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_1",
                                       OracleDbType = OracleDbType.Decimal,
                                       Direction = ParameterDirection.Input,
                                       Value = details.RuleId
                                   });
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_2",
                                       OracleDbType = OracleDbType.Decimal,
                                       Direction = ParameterDirection.Input,
                                       Value = details.CustomerDetails.CtiId
                                   });
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_3",
                                       OracleDbType = OracleDbType.Varchar2,
                                       Direction = ParameterDirection.Input,
                                       Value = details.CustomerDetails.Surname
                                   });
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_4",
                                       OracleDbType = OracleDbType.Varchar2,
                                       Direction = ParameterDirection.Input,
                                       Value = details.CustomerDetails.Postcode
                                   });
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_5",
                                       OracleDbType = OracleDbType.Date,
                                       Direction = ParameterDirection.Input,
                                       Value = details.CustomerDetails.DateOfBirth
                                   });
        command.Parameters.Add(new OracleParameter
                                   {
                                       ParameterName = "p_6",
                                       OracleDbType = OracleDbType.Varchar2,
                                       Direction = ParameterDirection.InputOutput
                                   });
        connection.Open();
        command.ExecuteNonQuery();
    }
}

我现在收到错误

  

“OCI-22303:输入”PACKAGENAME.TYPENAME“未找到”

对于UDTTYPENAME,我尝试了以下格式

  • TYPENAME
  • FUNCTIONNAME.TYPENAME
  • PACKAGENAME.TYPENAME
  • PACKAGENAME.TYPENAME
  • PACKAGENAME.FUNCTIONNAME.TYPENAME
  • SCHEMA.PACKAGENAME.TYPENAME

我很感激任何帮助和回应,因为我现在用完了想法。

1 个答案:

答案 0 :(得分:3)

实际上,你可以通过这个小小的自动化简化所有例程(程序,函数等)的转换和准备参数以及参考游标类型的参数

a)在公共包中定义以下类型和例程(让我们称之为utils)。

Type recRoutineSchema is Record (ColumnName varchar2(64),DataType Varchar2(20), ColumnOrder number, Direction varchar2(10), sSize nUMBER);

Type tblRoutineSchema is table of recRoutineSchema;

  function ftRoutineSchema(pkg varchar2,Routine varchar2) return  tblRoutineSchema  PIPELINED is 
      x recRoutineSchema;
       pkN  varchar2(100);
   rtN  varchar2(100);
   Begin 
     FOR Y in ( Select Argument_Name  ColumnName
                      ,Data_type      DataType
                      ,Position       ColumnOrder
                      ,In_out         Direction
                      ,Data_length    SSize 
                   from   user_ARGUMENTS 
                      where  package_Name=Upper(pkg) 
                         and object_name=Upper(Routine) order by position 
                         ) 
     LOOP
       PIPE ROW(Y);
     END LOOP;
     Return;  
   End;

b)和一个c#方法调用上面的函数来检索和设置你正在调用的过程/函数的参数

public void SetupParams(string RoutineName, OracleCommand cmd, IDictionary<string, string> prms, bool keepConnectionOpen = true)
            {
            Debug.WriteLine("Setting parameters for " + RoutineName);
            if (cmd != null) cmd.Parameters.Clear();
            string pname = "";
            string[] s = RoutineName.Split('.');
            DataTable tblParams = Select(String.Format("Select * from Table(pkgUtils.ftRoutineSchema('{0}','{1}')) ", s[0], s[1]));
           cmd.CommandText=RoutineName; 
           foreach (DataRow dr in tblParams.Rows)
                {
                using (OracleParameter p = new OracleParameter())
                    {
                    pname = dr["COLUMnNAME"].ToString() == "" ? "returnvalue" : pname = dr["COLUMnNAME"].ToString().ToLower();
                    if (prms.Keys.Contains(pname)) p.Value = prms[pname];
                    string direction = dr["Direction"].ToString().ToLower();
                    string sptype = (string)dr["DataType"];
                    string[] sx = dr["DataType"].ToString().Split(new char[] { '(', ',', ')' });
                    direction = pname == "returnvalue" ? "rc" : direction;
                    p.ParameterName = pname;
                    #region case type switch
                    switch (sx[0].ToLower())
                        {
                        case "number":
                            // p.DbType = OracleDbType.Decimal;
                            p.OracleDbType = OracleDbType.Decimal;
                            break;

                        case "varchar2":
                            p.DbType = DbType.String;
                            p.Size = 65536;
                            //  p.Size = prms[pname].Length;
                            // p.Size = int.Parse(sx[1]);
                            break;
                        case "ref cursor":
                            p.OracleDbType = OracleDbType.RefCursor;
                            // direction = "rc"; // force return value

                            break;
                        case "datetime":
                            p.DbType = DbType.DateTime;
                            break;
                        case "ntext":
                        case "text":
                            p.DbType = DbType.String;
                            p.Size = 65536;
                            break;
                        default:
                            break;
                        }
                    //-------------------------------------------------------------------------------
                    switch (direction)
                        {
                        case "in": p.Direction = ParameterDirection.Input; break;
                        case "out": p.Direction = ParameterDirection.Output; break;
                        case "in/out": p.Direction = ParameterDirection.InputOutput; break;
                        case "rc": p.Direction = ParameterDirection.ReturnValue; break;
                        default: break;
                        }

                    #endregion
                    cmd.Parameters.Add(p); ;
                    }
                }
            } 

C)。现在您可以轻松调用任何函数/ proc,如下所示,此过程实际上返回两个refcursor参数以弹出数据集。

 private void btnDumpExcel_Click(object sender, EventArgs e)
         {
         IDictionary<string, string> p = new Dictionary<string, string>();

         p.Add("pcomno", "020");
         p.Add("pcpls", "221");
         p.Add("pUploaderName", "Anthony Peiris");
         try
            {
            pGroupDs = O.execProc2DatSet("priceWorx.prSnapshotDiscounts", p, false, false);
            Excel.MakeWorkBook(ref pGroupDs, ref O, "1");

            }
         catch (Exception ex)
            {
            Debug.WriteLine(ex);
            Debugger.Break();
            }
         //Excel.MakeWorkBook(ref ds, ref O, "1");

         }

这是方法O.execProc2DataSet

public DataSet execProc2DatSet(string storedProcedureName, IDictionary<string, string> prms, bool propagateDbInfo, bool leaveConnectionOpen = false)
            {
           // initPackage(storedProcedureName.Substring(0,storedProcedureName.IndexOf('.')));
            try
                {
                using (OracleCommand cmd = new OracleCommand("", conn))
                    {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = storedProcedureName;
                    //dep = new OracleDependency(cmd);
                    //dep.OnChange += new OnChangeEventHandler(dep_OnChange);
                    if (prms != null) SetupParams(storedProcedureName, cmd, prms, true);
                    using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                        {
                        if (conn.State != ConnectionState.Open)
                            {
                            conn.Open();
                            cmd.Connection = conn;
                            }
                        using (DataSet ds = new DataSet())
                            {
                            da.Fill(ds);
                            return ds;
                            }
                        }
                    }
                }
            catch (Exception ex)
                {
                Debug.WriteLine(ex);
                Debugger.Break();
                return null;
                }
            finally
                {
                if (!leaveConnectionOpen) conn.Close();
                }
            }

这种方法允许您更改Proce / function参数,而不必担心自上次以来哪些参数可能已更改,因为参数设置现在是全自动的。 HTH