I have a stored procedure in Oracle which receives an input parameter of type varchar2 varying array. The procedure works and if you invoke it from SQL, what I need is called from C#.
My script is this:
CREATE OR REPLACE PROCEDURE INTEGRATOR.PRC_TEST_PARAM_ARRAY (p_nros_moviles integrator.NROMOVIL_ARRAY) IS
BEGIN
FOR i IN 1..p_nros_moviles.count LOOP
IF p_nros_moviles(i) IS NOT NULL THEN
INSERT INTO INTEGRATOR.TEST_PARAM_ARRAY VALUES (p_nros_moviles(i));
END IF;
END LOOP;
END;
/
My user type:
CREATE OR REPLACE TYPE INTEGRATOR.NROMOVIL_ARRAY AS
VARYING ARRAY(100) OF VARCHAR2(15);
/
My invoke from PLSQL
DECLARE
v_array integrator.NROMOVIL_ARRAY;
BEGIN
v_array := integrator.NROMOVIL_ARRAY('9999999', '66666666');
integrator.prc_test_param_array(v_array);
END;
And I try this way from c#
try
{
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" +
"(HOST=10.10.10.10)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)" +
"(SID=PORTANODE)));User Id=user;Password=*****;";
using (OracleCommand cmd = new OracleCommand("INTEGRATOR.PRC_TEST_PARAM_ARRAY", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter p = new OracleParameter();
p.ParameterName = "P_NROS_MOVILES";
p.OracleDbType = OracleDbType.Array;
p.Direction = ParameterDirection.Input;
p.UdtTypeName = "INTEGRATOR.NROMOVIL_ARRAY";
//p.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
p.Value = new string[] { "XXXX", "YYYY" };
cmd.Parameters.Add(p);
connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Ejecutado");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Someone could guide me I need to change to make it work
Be patient, Wait and wait.. it takes hell of a long time .. that is my experience
I'm not sure but I think that System.Data.OracleClient doesn't really support user defined arrays.
I'd try to write a helping stored function, which takes for example a comma separated string (these will be the values of your varray type), and splits it to values using WHILE LOOP and SUBSTR. Then in each iteration it adds the actual VARCHAR2 to a temporary integrator.NROMOVIL_ARRAY type variable using the EXTEND(1) to make place for the new value.
In the end the function returns the temporary integrator.NROMOVIL_ARRAY, and this value could be used in the stored procedure.
Related
What I need:
In PLS/SQL on an Oracle DB, create a stored procedure or function with parameters, which given a declared table of , where is a ROW of a table (with all the fields), returns the resultset following the conditions given in the parameters. After, I need to call them from Microsoft Entity Framework with edmx file.
Basically the need is to being able to provide a quick report of the table contents into a pdf, matching some filters, with an oracle db.
The mantainer must be able, provided a script I give, to create and add new reports, so this needs to be dynamic.
Here's what I've got so far:
CREATE OR REPLACE type THETABLEIWANTTYPE as table of THETABLEIWANT%TYPE
create function
SCHEMA.THETABLEIWANT_FUNCTION(PARAM_GR in number default 1)
return THETABLEIWANTTYPE
PIPELINED
as
result_table THETABLEIWANTTYPE
begin
SELECT S.id, S.idg, S.sta, S.tab
Bulk collect into result_table
from SCHEMA.THETABLEIWANT S
WHERE IDGR = PARAM_GR
IF result_table.count > 0 THEN
for i in result_table.FIRST .. result_table.LAST loop
pipe row (result_table(i))
end loop
end if
return
end;
But it's not working. It gives errors.
Running CREATE TYPE I get:
Compilation errors for TYPE SCHEMA.THETABLEIWANT
Error: PLS-00329: schema-level type has illegal reference to
SCHEMA.THETABLEIWANT
The mantainer will launch the script creating a TYPE of the row of the table I need, then the function should return a table with the records.
Then calling it from Entity Framework I should be able to execute it like I'm calling a normal select from my table, IE:
``_dbContext.THETABLEIWANT.Where(x => x.IDGR = Param_gr).ToList();
The problem is that mantainers should be able to generate new kind of reports with any select inside without the need of my intervention on the software code.
Any hint?
It's ok also to bulk all the select result into a temp table but it has to be dynamic as column will be changing
I ended up to write a PLS/SQL procedure that returns a cursor and managing it from C# code with Oracle.ManagedDataAccess Library.
Here's the procedure, for anyone interested:
CREATE OR REPLACE PROCEDURE SCHEMA.PROC_NAME(
PARAM_1 VARCHAR2,
RESULT OUT SYS_REFCURSOR)
IS
BEGIN
OPEN RESULT FOR
SELECT A, V, C AS MY_ALIAS from SCHEMA.TABLE WHERE FIELD = PARAM_1 AND FIELD_2 = 'X';
END;
And here's the C# code for calling and getting the result:
OracleConnection conn = new OracleConnection("CONNECTIONSTRING");
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
List<OracleParameter> parametri = new List<OracleParameter>()
{
new OracleParameter
{
ParameterName = nameof(filter.PARAM_1),
Direction = ParameterDirection.Input,
OracleDbType = OracleDbType.NVarchar2,
Value = filter.PARAM_1
}
};
OracleCommand cmd = conn.CreateCommand();
cmd.Parameters.AddRange(parametri.ToArray());
OracleParameter cursor = cmd.Parameters.Add(
new OracleParameter
{
ParameterName = "RESULT",
Direction = ParameterDirection.Output,
OracleDbType = OracleDbType.RefCursor
}
);
cmd.CommandText = procedureName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
using (OracleDataReader reader = ((OracleRefCursor)cursor.Value).GetDataReader())
{
if (reader.HasRows)
while (reader.Read())
{
//Iterate the result set
}
}
}
catch(Exception ex)
{
//Manage exception
}
I have a mystery with a stored procedure that I'm calling from code behind(C#). I am baffled because I have added watchpoints my code on the C# side and everything seems to be having the values that they should be going into the call to the stored procedure however, the procedure runs without any errors that I can tell and yet my table doesn't get updated with the values that I feel they should.
The SP gets three values passed to it.
Record ID (#Record_ID), Column to update (#UpdColumn), and the value to place in that column (#UpdValue).
Here is my SP that I am calling:
ALTER PROCEDURE [dbo].[Single_Col_Update]
-- Add the parameters for the stored procedure here
#Record_ID INT,
#UpdColumn CHAR,
#UpdValue NVARCHAR
AS
BEGIN
SET NOCOUNT ON;
IF #UpdColumn = 'TicketNumber'
UPDATE dbo.csr_refdata_ip360_HostVulnerabilityCSV
SET TicketNumber = #UpdValue
WHERE RecID = #Record_ID;
IF #UpdColumn = 'TicketClosed'
UPDATE dbo.csr_refdata_ip360_HostVulnerabilityCSV
SET TicketClosed = #UpdValue
WHERE RecID = #Record_ID;
IF #UpdColumn = 'Notes'
UPDATE dbo.csr_refdata_ip360_HostVulnerabilityCSV
SET Notes = #UpdValue
WHERE RecID = #Record_ID;
IF #UpdColumn = 'Exception_ID'
UPDATE dbo.csr_refdata_ip360_HostVulnerabilityCSV
SET ExceptionID = #UpdValue
WHERE RecID = #Record_ID;
END
Here is the code segment calling the SP:
foreach (string record in recordnumber)
{
SqlConnection con = new SqlConnection("Data Source=MyDataSource");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Single_Col_Update";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Record_ID", Convert.ToInt32(record));
cmd.Parameters.AddWithValue("#UpdColumn", Session["UpdColumn"]);
cmd.Parameters.AddWithValue("#UpdValue", Session["UpdValue"]);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Since all the variables are right, I'm not sure why this isn't updating. Hoping some of you may see an error here.
UPDATED 5/19/2017 1:40PM Central -
Steve,
I attempted to implement the call as you prescribed below. I only made to variations to what you provided:
'cmd.Parameters.Add("#UpdValue", SqlDbType.NVarChar, 1024);' // instead of 255 because the column I'm feeding there is an NVarChar(MAX) I will likely have to go back and modify this to be greater than 1024. There didn't appear to be a MAX value that I could put in there so for testing the 1024 will suffice.
omitted the 'transaction.Rollback();' // I kept red lining on the word 'transaction' and despite what I tried I couldn't get it to validate it.
Bottom line is that after implementing the code below the results were exactly the same as before. The code executed without reporting any errors either via the Consol.Write I added or through the VS 2017 IDE.
SqlTransaction transaction;
try
{
using (SqlConnection con = new SqlConnection("Data Source=MyDataSource"))
using (SqlCommand cmd = new SqlCommand("Single_Col_Update", con))
{
con.Open();
transaction = con.BeginTransaction();
cmd.Transaction = transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Record_ID", SqlDbType.Int);
cmd.Parameters.Add("#UpdColumn", SqlDbType.NVarChar, 255);
cmd.Parameters.Add("#UpdValue", SqlDbType.NVarChar, 1024);
foreach (string record in recordnumber)
{
cmd.Parameters["#Record_ID"].Value = Convert.ToInt32(record);
cmd.Parameters["#UpdColumn"].Value = Session["UpdColumn"].ToString();
cmd.Parameters["#UpdValue"].Value = Session["UpdValue"].ToString();
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
So I'm still where I was, but I have taken notice of what you shared and I concur with all you stated. I hadn't noticed that I was opening and closing the connection there and was not aware of other things you had shared.
However the quandary remains!
Update 05/22/2017 10:45AM Central time:
I realized that I was trying to stuff NVarchar type into to a Varchar type in my stored procedure. Once corrected the modifications that I made based on Steve's feedback worked just fine. I haven't tried it but I'm assuming that what I had to begin with would have worked if the types had matched to begin with, but Steve's example is cleaner so I am not even going back to test the old way. Thanks again Steve!
The problem is in the declaration of this parameter
#UpdColumn CHAR,
in this way the Stored Procedure expects a SINGLE char, not a string.
Thus all the following if statements are false and nothing will be updated
Change it to
#UpdColumn NVARCHAR(255)
The same is true for the #UpdValue parameter. Again, only a single char is received by the stored procedure. Doesn't matter if you pass a whole string.
If you don't specify the size of the NVARCHAR or CHAR parameters the database engine will use only the first char of the passed value.
I want also to underline the comment above from Alex K. While it should not give you a lot of gain it is preferable to open the connection and create the command with the parameters outside the loop. Inside the loop just change the parameters values and execute the sp
SqlTransaction transaction;
try
{
using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand("Single_Col_Update", con))
{
con.Open();
transaction = con.BeginTransaction())
cmd.Transaction = transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Record_ID", SqlDbType.Int);
cmd.Parameters.Add("#UpdColumn", SqlDbType.NVarChar, 255);
cmd.Parameters.Add("#UpdValue", SqlDbType.NVarChar, 255);
foreach (string record in recordnumber)
{
cmd.Parameters["#Record_ID"].Value = Convert.ToInt32(record));
cmd.Parameters["#UpdColumn"].Value = Session["UpdColumn"].ToString();
cmd.Parameters["#UpdValue"].Value = Session["UpdValue"].ToString();
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
catch(Exception ex)
{
// show a message to your users
transaction.Rollback();
}
I have also added all your loop inside a transaction to confirm all the inserts as a whole or reject all in case of errors.
CHAR should only be used when a column is a fixed length. When you use it with varying length strings, the results will be usually not what you expect because the parameter/column will be padded with spaces which is why your IF statements are failing.
Don't use the CHAR type for #UpdColumn. Use NVARCHAR instead for this column and also it's a good practice to specify a length for both this parameter and the UpdValue parameter in your stored procedure and then match this closely when calling the stored procedure from your C# code.
I've created a procedure for test this problem and it works right in oracle developer. There is a typed named "dizi" (array and varchar2). And procedure has input parameter. I'm trying to pass an array to this to this procedure as a parameter in c#. I've searched a lot but i couldn't solve the problem. The error is: "Not all veriables bound"
public void InsertQuestion(List<string> area_list)
{
quest_areas = area_list.ToArray();
command = new OracleCommand();
command.Connection = connect;
connect.Open();
var arry = command.Parameters.Add("area_array",OracleDbType.Varchar2);
arry.Direction = ParameterDirection.Input;
arry.Size = quest_areas.Length;
arry.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
arry.Value = quest_areas;
command.BindByName = true;
command.CommandText ="TESTPROCEDURE(:area_array)";
command.CommandType = CommandType.StoredProcedure;
command.ExecuteNonQuery();
connect.Close();
}
Here is my procedure (it is just for test but i'll use something like that)
CREATE OR REPLACE PROCEDURE TESTPROCEDURE (t_in IN dizi)
IS
BEGIN
FOR i IN 1..t_in.count LOOP
dbms_output.put_line(t_in(i));
END LOOP;
END;
I've got code that successfully passes array down to oracle sprocs. Takes a slightly different approach to yours. Not entirely sure how much is relevant, but in case it helps my code:
uses the correct name parameter name (t_in in your case)
doesn't bother setting the size of the parameter
creates an object array that is the correct length and copies the contents across into it (ie from quest_areas in your case)
then sets this object array as the Value for the command parameter
doesn't use bind variables when calling the proc, rather just uses the proc name by itself as the CommandText.
That said, I suspect your problem might be around your use of a bind variable when calling the procedure. What happens if you just set 'TESTPROCEDURE' as the CommandText?
Or go the other way and put change it into a proper anonymous PLSQL block 'begin TESTPROCEDURE(:area_array); end;' and change the CommandType to CommandType.Text (as just suggested by Wernfried while I was typing...)
Update
public void InsertQuestion(List<string> area_list)
{
var input_array = area_list.Select(s => (object)s).ToArray();
command = new OracleCommand();
command.Connection = connect;
connect.Open();
var arry = command.Parameters.Add("area_array",OracleDbType.Varchar2);
arry.Direction = ParameterDirection.Input;
arry.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
arry.Value = input_array;
command.CommandText ="TESTPROCEDURE";
command.CommandType = CommandType.StoredProcedure;
command.ExecuteNonQuery();
connect.Close();
}
I'm having problems executing a function in one of my oracle packages from c#. The following is my code for opening the connection and executing the function:
Decimal firstID = Decimal.Parse("2453699");// This values are just for testing
string secondID = "12345";
Decimal sec = Decimal.Parse("1");
string estatus = "TEXT";
OracleConnection con = new OracleConnection();
con.ConnectionString = "User Id=user;Password=the_pass;Data Source=Data_Source";
con.Open();
string sql = "Package.F_FUNCTION_1";
OracleCommand com = new OracleCommand(sql, con);
com.CommandType = System.Data.CommandType.StoredProcedure;
com.Parameters.Add("returnVal", OracleDbType.Varchar2, 32767);
com.Parameters["returnVal"].Direction = System.Data.ParameterDirection.ReturnValue;
com.Parameters.Add("v_firstID",OracleDbType.Decimal,10);
com.Parameters.Add("v_secondID", OracleDbType.Varchar2,200);
com.Parameters.Add("p_sec", OracleDbType.Decimal, 3);
com.Parameters.Add("p_estatus", OracleDbType.Varchar2,50);
com.Parameters["v_firstID"].Value = firstID;
com.Parameters["v_secondID"].Value = secondID;
com.Parameters["p_sec"].Value = sec;
com.Parameters["p_estatus"].Value = estatus;
com.ExecuteNonQuery();
string val = com.Parameters["returnVal"].Value.ToString();
con.Close();
And the following is the function in my package, which needs to call a second function in the same package:
FUNCTION F_FUNCTION_1(v_firstID IN NUMBER,
v_secondID IN VARCHAR2
,p_sec IN NUMBER DEFAULT NULL
,p_estatus IN VARCHAR2 DEFAULT NULL)
RETURN VARCHAR2 AS
v_Return VARCHAR2(200) := '';
secuencia VARCHAR2(1000) := null;
secc VARCHAR2(1000) := NULL;
BEGIN
-- Some validations
v_Return := Package.F_FUNCTION_2(
v_secondID => v_secondID,
P_SEC => p_sec,
P_ESTATUS => p_estatus
);
return v_Return;
END F_FUNCTION_1;
FUNCTION F_FUNCTION_2(v_secondID IN VARCHAR2
,p_sec IN NUMBER DEFAULT NULL
,p_estatus IN VARCHAR2 DEFAULT NULL)
RETURN VARCHAR2 AS
--some variables
v_URL VARCHAR2(500) := NULL;
BEGIN
--A lot of code here that works
RETURN v_URL;
END F_FUNCTION_2;
The problem is: when i run this code, i get the error:
ORA-01460: unimplemented or unreasonable conversion requested
I suppose it is related to the parameters types. I'v tried changing types, using ExecuteScalar instead of ExecuteNonQuery, changing the syntax of the parameters addition to the command... but they didn't work.
I know it's easy but I have a brain lock now.
Hope someone can help.
For this to work you need to add a parameter to your oracle function as an OUT parameter and then extract the parameter as you are doing after using ExecuteNonQuery. I would add the OUT parameter as the first one in your F_FUNCTION_1 function.
I have a (simplified) Oracle SQL like this:
declare
xd number;
xm number;
DataOut sys_refcursor;
begin
xd := to_number(to_char(sysdate, 'dd'));
xm := to_number(to_char(sysdate, 'mm'));
open DataOut for
select * from dual;
end;
And I want to be able to fill a DataTable in .Net from the data returned in the DataOut parameter.
I have been trying various things but can't seem to access the DataOut cursor.
How would I call this?
OracleCommand c = new OracleCommand();
c.CommandType = CommandType.Text;
c.CommandText = SQL;
OracleParameter param = new OracleParameter();
param.Direction = ParameterDirection.Output;
param.OracleType = OracleType.Cursor;
param.ParameterName = "DataOut";
c.Parameters.Add(param);
c.Connection = (OracleConnection) this.GetConnection();
OracleString rowNum = "";
c.ExecuteOracleNonQuery(out rowNum);
// or c.ExecuteReader()
// or use OracleDataAdapter
DataTable returnTable = /* magic goes here */
I can edit the SQL but I'm not able to create functions or procedures.
Is this possible?
An anonymous PL/SQL block does not return anything so you won't be able to use the cursor you open in the anonymous PL/SQL block in your client application. In order to return the data to the client application, you would need to use a named PL/SQL block (i.e. a stored procedure or a stored function). If you are not allowed to create named PL/SQL blocks, you won't be able to return a cursor you open in PL/SQL to your client application.
select cursor(select * from dual) from dual;