I am trying to call an Oracle function from C# that returns multiple rows but it is not working. Here is the function I am using:
create or replace function return_columns(
tableName IN varchar
)
return types.ref_c
as
c_result types.ref_c;
begin
open c_result for
select column_name
from all_tab_columns
where table_name = tableName;
return c_result;
end return_columns;
Here is the type:
create or replace package types
as
type ref_c is ref cursor;
end;
I am in C# code calling the function like this:
OracleConnection oraConn = new OracleConnection("DATA SOURCE=MySource;PASSWORD=MyPassword;USER ID=MyID");
OracleCommand objCmd = new OracleCommand("MyID.RETURN_COLUMNS", oraConn);
objCmd.CommandType = CommandType.StoredProcedure;
OracleParameter oraParam = new OracleParameter("tableName", OracleType.VarChar);
oraParam.Value = "MY_TABLE";
oraCmd.Parameters.Add(oraParam);
oraConn .Open();
DataTable dt = new DataTable();
OracleDataAdapter ad = new OracleDataAdapter(objCmd);
ad.Fill(dt);
oraConn.Close();
And it keeps returning this error:
'RETURN_COLUMNS' is not a procedure or is undefined ORA-06550: line 1, column 7: PL/SQL: Statement ignored
What is wrong with my Oracle function?
You simply need to define one more parameter, a parameter responsible for return value. Here is an example:
OracleParameter retVal = new OracleParameter("retVal", OracleDbType.RefCursor);
retVal.Direction = ParameterDirection.ReturnValue;
Note #1: The retVal
parameter should be added first in the parameter list, otherwise you might receive ORA-00306: wrong number or type of arguments..
error.
cmd.Parameters.Add(retVal); -- ReturnValue parameter is being added first
cmd.Parameters.Add(tabName); -- then goes everything else
Note #2: It would be better to use ODP for .NET instead of obsolete and deprecated Microsoft Oracle client (System.Data.OracleClient
)
Note #3: Use varchar2
data type instead of varchar
in your PL/SQL code. As of now they are synonyms but their behavior might change in the future.