I need to call to some function and procedures that in packages in Oracle.
I never worked with oracle, and i know only basic staff like insert,update table, but now i need to call "vb_new_serial " function to get back from it integer here this function function vb_new_serial return integer;
This function is located in Packages VN_PKG -> vb_new_serial
Here my code that i tried after i did some reasearches:
using (var conn = new OracleConnection(strConn2))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "vb_new_serial";
conn.Open();
using (var dr = cmd.ExecuteReader())
{
MessageBox.Show(dr.ToString());
}
}
}
Here the image
But here i did't get back nothing.
What i am doing wrong?
Is there any parameters need to add in oracle command ? because return value is the first parameter added to the oracle command.
Like this
cmd.Parameters.Add("Return_Value", OracleDbType.Int16,
ParameterDirection.ReturnValue);
You just need to change your code in order to get the integer that the Oracle function returns:
using (var conn = new OracleConnection(strConn2))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "VN_PKG.vb_new_serial";
OracleParameter myReturn = new OracleParameter("myReturn", OracleDbType.Int32, ParameterDirection.ReturnValue);
cmd.Parameters.Add(myReturn);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(myReturn.Value.ToString());
}
}
Related
I'm new in c# and want to call store procedure in the sql server database ,for that purpose write this code:
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;"))
{
using (SqlCommand cmd = new SqlCommand("exec web.sp_getTotalBillPayam "+Convert.ToInt64(phoneNumber) +",'"+password.Trim()+"',72107603,1067", con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
when run that code every thing is ok but store procedure not return to me any result ,goto debug i realized in this line run:
SqlDataReader reader = cmd.ExecuteReader();
but debugger not go to the next line of code and wait that line run finish,after 5 min that line not finish and dont go next line of code,what happen?How can i solve that problem?thanks.
Your command is not attached to your connection-- and your use of parameters is dangerous. Try this instead:
EDIT: Sorry, your command is attached to the connection, didn't see that being passed in. Either way, this is the correct pattern for calling a stored proc
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;")) {
con.Open();
using (SqlCommand cmd = con.CreateCommand()) {
cmd.CommandText = "web.sp_getTotalBillPayam";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//repeat this for each parameter
var parameter = cmd.CreateParameter();
parameter.ParameterName = "PhoneNumber"; //this must match whatever your parameters are to your stored proc
parameter.DbType = System.Data.DbType.Int64;
parameter.Direction = System.Data.ParameterDirection.Input;
parameter.Value = phoneNumber;
cmd.Parameters.Add(parameter);
...
//if you have an OUTPUT result from your proc, add a a parameter called RETURNS with a direction of ParameterDirection.Return and check value AFTER executing
using (SqlDataReader reader = cmd.ExecuteReader()) {
//if your results are a SELECT query they will be here
}
}
}
IN THE LAST PART I WROTE THE working solution:
I have this stored procedure in SQL Server :
alter PROCEDURE [dbo].[ProcedureName]
#v nvarchar(10),
#L NVarChar(2)
AS
BEGIN
SET NOCOUNT ON;
SELECT B,M,V
FROM XXXX
WHERE V = #v and L = #L
END
and I am passing the parameters but I cannot retrieve the SELECT part I need to retrieve B,M,V of Select B,M,V also
SqlCommand Cmd = new SqlCommand("ProcedureName", cnn);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#v", SqlDbType.NVarChar, 10).Value = v;
Cmd.Parameters.Add("#L", SqlDbType.NVarChar, 2).Value = lo;
if (Cmd.Connection.State == ConnectionState.Closed)
{
Cmd.Connection.Open();
}
Cmd.ExecuteNonQuery();
THIS IS THE WOKING SOLUTION THANKS TO THE HELP I GOT HERE :
SqlCommand Cmd = new SqlCommand("ProcedureName", cnn);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#v", SqlDbType.NVarChar, 10).Value = v;
Cmd.Parameters.Add("#L", SqlDbType.NVarChar, 2).Value = lo;
if (Cmd.Connection.State == ConnectionState.Closed)
{
Cmd.Connection.Open();
}
using (SqlDataReader reader = Cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
ret = new MYCLASS();
ret.B = reader.GetString(0);
ret.M = reader.GetString(1);
ret.V = reader.GetString(2);
}
}
}
You'll need to make use of SqlDataReader to achieve this. Also make use of using block to ensure the connection object is closed and disposed correctly.
From MSDN
To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
You can change your code to something like:
using(var con = new SqlConnection("ConnectionString")) {
using(var cmd = new SqlCommand("ProcedureName", con)) {
//Params here
con.Open();
using(var reader = cmd.ExecuteReader()) {
while (reader.Read()) {
var bValue = reader.GetString(0);
//Same for the next two values
}
}
}
}
You're almost there, now if you pay close attention to your code you're not using the correct method for your procedure. This can be easily achieved with:
ExecuteReader Since you're only reading from your database.
instead of:
ExecuteNonQuery which is commonly used for UPDATE, INSERT, or DELETE statements
In C# code I'm trying to load a data table from an Oracle function. The function has a SYS_REFCURSOR return type. This is my code that tries to populate a DataTable dt using the function:
using (var connection = new OracleConnection(connstring))
{
connection.Open();
using (var command = new OracleCommand())
{
command.Connection = connection;
command.CommandText = "FNC_AXA_APPTS";
command.CommandType = CommandType.StoredProcedure;
OracleParameter retVal = new OracleParameter("PRS", OracleDbType.RefCursor);
retVal.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(retVal);
command.Parameters.Add(new OracleParameter("EG_PARAM", OracleDbType.Varchar2, 50)).Value = paramValue;
command.ExecuteNonQuery();
using (OracleDataReader reader = ((OracleRefCursor)command.Parameters["PRS"].Value).GetDataReader())
{
dt.Load(reader);
}
}
}
In some cases the Oracle function uses a dblink to a SQL databases. In those cases I'm getting the following exceptions...
ORA-01002: fetch out of sequence
ORA-02063: preceding line from GATE_LINK
... where GATE_LINK is the dblink. My research so far confirms that the issue must lie with the dblink.
We're using the Oracle Data Provider for .NET - is it possible this doesn't support dblink to SQL Server? Or if it does, what can I configure at the SQL end to resolve this?
I should mention that we're connecting to the Oracle DB over a VPN and the connection string uses the following format:
"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));User Id={3};Password={4};"
Thanks in advance...
Having spent over a day investigating this I was directed to the answer just 10 minutes after posting my question. Typical!
The answer was found here - https://community.oracle.com/thread/659625 - and all that's required is to wrap the calling code in a transaction. Working code looks like this:
using (var connection = new OracleConnection(connstring))
{
connection.Open();
using (var command = connection.CreateCommand())
{
// Start a local transaction
using (var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted))
{
// Assign transaction object for a pending local transaction
command.Transaction = transaction;
command.CommandText = "FNC_AXA_APPTS";
command.CommandType = CommandType.StoredProcedure;
OracleParameter retVal = new OracleParameter("PRS", OracleDbType.RefCursor);
retVal.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(retVal);
command.Parameters.Add(new OracleParameter("EG_PARAM", OracleDbType.Varchar2, 50)).Value = paramValue;
command.ExecuteNonQuery();
using (OracleDataReader reader = ((OracleRefCursor)command.Parameters["PRS"].Value).GetDataReader())
{
dt.Load(reader);
}
}
}
}
My limited understanding of the solution is that without this a transaction is committed at the SQL Server end which causes the returned cursor to fail in its iteration once passed to the .NET code. If anyone has a better explanation please add to this question.
this is valueable solution
using (var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted))
{
...
I can do it now, so much tks
I am having a problem with an Output parameter in C#/Oracle. I have isolated the code that I need to get working.
This is part of a much larger SQL statement, so do not worry too much if it doesn't make sense. In short I need to copy a row, give it a new ID and return that new ID. I tried using "RETURNING" which did not work. I see no reason why the code below should not work, but I'm getting an "ORA-01036: illegal variable name/number" error. Can anyone see what I'm doing wrong?
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "SELECT seq.nextval INTO :outValue FROM dual";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
// This is just to see the exception when it fails.
}
}
}
The name of the parameter doesn't match.
cmd.Parameters.Add(":outValue", OracleType.Int32).Direction.......;
^
I have also seen this variation on the query syntax
"BEGIN SELECT seq.nextval INTO :outValue FROM dual END;"
You are using named parameters. Try setting:
cmd.BindByName = true;
Have you tried 'returning' keyword like this?
This code works for me.
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "insert into table (id, value) values (seq.nextval, 'value') returning id into :outValue";
cmd.ExecuteNonQuery();
}
}
This is a really, really stupid question but I am so accustomed to using linq / other methods for connecting and querying a database that I never stopped to learn how to do it from the ground up.
Question: How do I establish a manual connection to a database and pass it a string param in C#? (yes, I know.. pure ignorance).
Thanks
using (SqlConnection conn = new SqlConnection(databaseConnectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", fileID);
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}
}
One uses the SqlCommand class to execute commands (either stored procedures or sql) on SQL Server using ado.net. Tutorials abound.
Here's an example from http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
public void RunStoredProcParams()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
// typically obtained from user
// input, but we take a short cut
string custId = "FURIB";
Console.WriteLine("\nCustomer Order History:\n");
try
{
// create and open a connection object
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand(
"CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-35} Total: {1,2}",
rdr["ProductName"],
rdr["Total"]);
}
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
3 things no one else has shown you yet:
"Stacking" using statements
Setting an explicit parameter type rather than letting .Net try to pick one for you
"var" keyword
.
string sql = "MyProcedureName";
using (var cn = new SqlConnection(databaseConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ParameterName", SqlDbType.VarChar, 50)
.Value = "MyParameterValue";
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}