Is it possible to correctly pass an OracleParameter to a boolean parameter in a pl/sql stored procedure?
I used the following workaround to bypass this limitation:
Wrap the function call using an anonymous block.
Return an output variable containing 1 or 0.
Read the output variable and cast it to boolean.
Here is some sample code:
using (var connection = new OracleConnection("<connection string>"))
{
var command = new OracleCommand();
command.Connection = connection;
command.CommandText =
"declare v_bool boolean;" +
"begin " +
"v_bool := auth_com.is_valid_username (:username); "+
"if (v_bool = TRUE) then select 1 into :v_result from dual; end if; " +
"if (v_bool = FALSE) then select 0 into :v_result from dual; end if; " +
"end;";
command.Parameters.Add(new OracleParameter { ParameterName = "username", OracleDbType = OracleDbType.NVarchar2, Size=512, Direction = ParameterDirection.Input });
command.Parameters.Add(new OracleParameter { ParameterName = "v_result", OracleDbType = OracleDbType.Decimal, Direction = ParameterDirection.Output });
try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
bool success = Convert.ToBoolean(((OracleDecimal)command.Parameters["v_result"].Value).ToInt32());
}
EDIT:
Alex Keh from Oracle, october 2013:
We're planning on supporting ODP.NET Boolean in the managed provider
in the near term, possibly in the middle of next year.
You can not use boolean parameters in SQL. So calling an stored procedure that takes or returns a boolean value won't work in SQL. There is no problem using such a procedure from within a pl/sql block.
ADDED from JCallico answer:
I used the following workaround to bypass this limitation:
Wrap the function call using an anonymous block.
Return an output variable containing 1 or 0.
Read the output variable and cast it to boolean.
Here is some sample code:
using (var connection = new OracleConnection("<connection string>"))
{
var command = new OracleCommand();
command.Connection = connection;
command.CommandText =
"declare v_bool boolean;" +
"begin " +
"v_bool := auth_com.is_valid_username (:username); "+
"if (v_bool = TRUE) then select 1 into :v_result from dual; end if; " +
"if (v_bool = FALSE) then select 0 into :v_result from dual; end if; " +
"end;";
command.Parameters.Add(new OracleParameter { ParameterName = "username", OracleDbType = OracleDbType.NVarchar2, Size=512, Direction = ParameterDirection.Input });
command.Parameters.Add(new OracleParameter { ParameterName = "v_result", OracleDbType = OracleDbType.Decimal, Direction = ParameterDirection.Output });
try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
bool success = Convert.ToBoolean(((OracleDecimal)command.Parameters["v_result"].Value).ToInt32());
}
EDIT:
Alex Keh from Oracle, october 2013:
We're planning on supporting ODP.NET Boolean in the managed provider
in the near term, possibly in the middle of next year.
Related
.net core 3.1
nuget: Oracle.ManagedDataAccess.Core 2.19.91
Oracle function:
create or replace NONEDITIONABLE FUNCTION GET_TOTAL_SALES
(
PARAM1 IN VARCHAR2,
PARAM2 IN VARCHAR2
)
RETURN VARCHAR2 AS
BEGIN
RETURN 'abc';
END GET_TOTAL_SALES;
.net core code:
var cmdText = "GET_TOTAL_SALES";
using (var connection = new OracleConnection(connStr))
{
using (var command = new OracleCommand(cmdText, connection))
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
var param1 = new OracleParameter("PARAM1", OracleDbType.Varchar2);
param1.Direction = ParameterDirection.Input;
param1.Value = "param1Value";
command.Parameters.Add(param1);
var param2 = new OracleParameter("PARAM2", OracleDbType.Varchar2);
param2.Direction = ParameterDirection.Input;
param2.Value = "param2Value";
command.Parameters.Add(param2);
var returnValue = new OracleParameter("returnValue", OracleDbType.Varchar2);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
command.ExecuteNonQuery();
Console.WriteLine(returnValue.Value); //""
Console.WriteLine(param1.Value); //"abc"
}
}
The result is that the returned value is putted into the first parameter (param1) and not into the returnValue. Why? Help!
I asked Oracle and got a reply:
"This is expected behavior. The first parameter bound for a function must be the return value. From the doc:
https://docs.oracle.com/en/database/oracle/oracle-data-access-components/19.3.2/odpnt/featOraCommand.html
I know, it is crazy.
We can also use binding by name:
command.BindByName = true;
and then order doesn't matter.
I am testing Oracle database. I wrote some code but my datareader has no rows, why? My "carros" table has data and I am selecting all of them but I am getting an empty result set it seems.
string constr = "Data Source=localhost:1521/XE;User Id=System;Password=password;";
OracleConnection con = new OracleConnection(constr);
OracleCommand oracleCommand = new OracleCommand();
oracleCommand.Connection = con;
oracleCommand.CommandText = "select preco from carro";
con.Open();
OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
string resultado = String.Empty;
//My test, I got hasRows as false
if (oracleDataReader.HasRows == false)
{
resultado = "no results";
}
//never enters this loop.
while (oracleDataReader.Read())
{
resultado += (string)oracleDataReader["preco"];
}
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
return resultado;
If HasRows is false after ExecuteReader, the problem is simply that the query is returning no rows so Read will return false as well. Perhaps the someValue variable is not set correctly.
From you description, it seems that your table is named carros while your query has used carro. Try to use
oracleCommand.CommandText = "select preco from carros";
A path towards solving this can include a scattering of logging commands that write to the file system.
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", "put error message here" + "\r\n");
Or for printing a variable:
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", ex.ToString() + "\r\n");
Pepper variations of this command throughout your script to see where failures are happening and to validate variable values.
I am attempting to execute a stored procedure that has several in/out parameters. This is what the expected way of doing this with SQLServer would be.
using (Context)
{
const string xml = "<test><testc>testing</testc></test>";
var userIdParam = new SqlParameter { ParameterName = "I_USER_ID", Value = user.ID };
var dtsParam = new SqlParameter { ParameterName = "I_DTS", Value = DateTime.Now };
var timeoutParam = new SqlParameter { ParameterName = "I_TIMEOUT", Value = DateTime.Now };
var xmlParam = new SqlParameter { ParameterName = "I_XML", Value = xml };
var sessionIdParam = new SqlParameter { ParameterName = "O_SESSION_ID", Value = "", Direction = ParameterDirection.Output };
var result =
Context.Database.SqlQuery<string>(
"DALLEN.SP_INSERT_SESSION I_USER_ID, I_DTS, I_TIMEOUT, I_XML, O_SESSION_ID out",
userIdParam,
dtsParam,
timeoutParam,
xmlParam,
sessionIdParam);
}
Unfortunately this does not work with oracle. I understand that ref cursors might be used in place of out parameters but that is not my own issue. Is there a good way of passing parameters to the stored procedure using dbcontext.database.sqlquery?
EDIT
Error message received when the query attempts to execute. It explains that it doesn't accept sqlParamters so I changed them to OracleParamters and that didn't work either.
"Unable to cast object of type 'System.Data.SqlClient.SqlParameter' to type 'Oracle.DataAccess.Client.OracleParameter'."
Procedure:
CREATE OR REPLACE PROCEDURE DALLEN.SP_INSERT_SESSION (
I_USER_ID IN NUMBER,
I_DTS IN DATE,
I_TIMEOUT IN DATE,
I_XML IN VARCHAR2,
O_SESSION_ID OUT NUMBER
)
AS
BEGIN
SELECT S_SESSION.NEXTVAL
INTO O_SESSION_ID
FROM DUAL;
INSERT INTO DALLEN.SYS_SESSION
(ID, USER_ID, DTS, TIMEOUT, XML)
VALUES (O_SESSION_ID, I_USER_ID, I_DTS, I_TIMEOUT, I_XML);
END;
Thank you in advance!
I am wrote stored procedure to Insert data into database table but i am not getting how to pass datatable to stored procedure kindly tell how to use it.
below is my storedprocedure
CREATE OR REPLACE PROCEDURE PR_SREE_TEST(p_recordset In SYS_REFCURSOR) IS
Contrac_rc SREE_TEST%rowtype;
BEGIN
Loop
Fetch p_recordset Into Contrac_rc;
EXIT WHEN p_recordset%NOTFOUND;
Insert into SREE_TEST(CT,DESC,FLAG)
Values(Contrac_rc.CT,Contrac_rc.DESC,Contrac_rc.FLAG);
End Loop;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
WHEN OTHERS THEN
-- Consider logging the error and then re-raise
RAISE;
END PR_SREE_TEST;
/
and cs page
public DataSet sreetest(DataTable dt)
{
DataSet dsRegularIndentdtl = new DataSet();
try
{
OracleConnection OraConn = new OracleConnection(strDBConnection);
OraConn.Open();
OracleCommand OraCmd = new OracleCommand();
OraCmd.Connection = OraConn;
OraCmd.CommandText = "PR_SREE_TEST";
OraCmd.CommandType = CommandType.StoredProcedure;
OracleParameter parameter = new OracleParameter();
var recordSet1 = new DataTable();
recordSet1 = dt;
OraCmd.Parameters.Add("p_recordset", OracleDbType.RefCursor, recordSet1, ParameterDirection.Input);
OraCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
return dsRegularIndentdtl;
}
}
above is my code it is saying that p_recordset not valied. please tell me how to execute it.
Make sure you are using the correct overload of OraCmd.Parameters.Add(),
As per msdn the fourth parameter is not parameter direction, it is as below
public OracleParameter Add(
string parameterName,
OracleType dataType,
int size,
string srcColumn
)
I am inserting values in to Database from a Webform using ADO.NET, C#. DB I am using is Oracle Database. Values are not being inserted and the program gets struck at the cmd.ExecuteNonquery()
Here is my Code below, Please let me know If I am doing any mistake.. I am using some Static Methods will that be any problem ?..
public Boolean AddDivCo(Int32 UserNo,String ID, String Role, String DivName )
{
Boolean ret = false;
OracleCommand cmd = new OracleCommand();
OracleConnection conn = new OracleConnection();
int i = 0;
try
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Conn_RIS"].ConnectionString;
conn.Open();
cmd.Connection = conn;
String mySQL = "INSERT INTO R4CAD_ADMIN (AdminUserNo, AdminID, AdminRole, AdminDivName)VALUES(:AdminUserNo,:AdminID,:AdminRole,:DivName)";
OracleParameter p1 = new OracleParameter("AdminUserNo", OracleType.Number);
p1.Value = UserNo;
cmd.Parameters.Add(p1);
OracleParameter p2 = new OracleParameter("AdminID", OracleType.VarChar);
p2.Value = ID;
cmd.Parameters.Add(p2);
OracleParameter p3 = new OracleParameter("AdminRole", OracleType.VarChar);
p3.Value = Role;
cmd.Parameters.Add(p3);
OracleParameter p4 = new OracleParameter("DivName", OracleType.VarChar);
p4.Value = DivName;
cmd.Parameters.Add(p4);
cmd.CommandText = mySQL;
i = cmd.ExecuteNonQuery();
if (i != 0)
{
ret = true;
}
else
{
ret = false;
}
}
catch (Exception err)
{
Console.WriteLine(err.Message.ToString());
}
finally
{
cmd.Dispose();
//cmd = null;
//conn = null;
conn.Close();
}
return ret;
}
Is there a primary key defined on this table? If so, then my guess is that you have another session that already has inserted a record with this key, but has not yet terminated the transaction with a commit or rollback. I don't see a commit as part of your code - I assume you're doing that somewhere else?
Execute your code above once more, and while it's hung run the following query from another session:
SELECT
(SELECT username FROM v$session WHERE sid=a.sid) blocker,
a.sid,
' is blocking ',
(SELECT username FROM v$session WHERE sid=b.sid) blockee,
b.sid
FROM v$lock a JOIN v$lock b ON (a.id1 = b.id1 AND a.id2 = b.id2)
WHERE a.block = 1
AND b.request > 0;
This should tell you if you're being blocked by another session and what the SID is of that session.