how to get oracle stored procedure standard output in c# - c#

I am trying to get the stand output in c# returned from oracle stored procedure. dbms_output.put_line('Hello Word')
The c# code i am using is
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = My_connection_string;
con.Open();
OracleCommand cmd = new OracleCommand("tmp_test", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
var result = cmd.ExecuteScalar();
}
The oracle stored procedure code is
create or replace procedure tmp_test as
v_count integer;
begin
dbms_output.put_line('Hello Word');
end;
The stored procedure execute successfully but I can't get the Hello Word back.

After some struggle i have managed to find the answer and decided to post that might help other.
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = My_connection_string;
con.Open();
OracleCommand cmd = new OracleCommand("tmp_test", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
var result = cmd.ExecuteScalar();
//it is included dbms_output
cmd.CommandText = "begin dbms_output.enable (1000); end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
string out_string;
int status = 0;
cmd.CommandText = "BEGIN DBMS_OUTPUT.GET_LINE (:out_string, :status); END;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.Parameters.Add("out_string", OracleType.VarChar, 32000);
cmd.Parameters.Add("status", OracleType.Double);
cmd.Parameters[0].Direction = System.Data.ParameterDirection.Output;
cmd.Parameters[1].Direction = System.Data.ParameterDirection.Output;
cmd.ExecuteNonQuery();
out_string = cmd.Parameters[0].Value.ToString();
status = int.Parse(cmd.Parameters[1].Value.ToString());
}

Here's a link to a the documentation for DBMS_OUTPUT package in Oracle - DBMS_OUTPUT
It specifically states that it's used for debugging Oracle Stored Procedures and that this is in essence a debug buffer that you need to actively poll use GET_LINES in order to see the output.

Function in PL/SQL should be something like this:
create or replace function tmp_test as
begin
RETURN 'Hello World';
end;

Related

Execute/ Call Oracle Procedure In C# [duplicate]

How does one call a stored procedure in oracle from C#?
Please visit this ODP site set up by oracle for Microsoft OracleClient Developers:
http://www.oracle.com/technetwork/topics/dotnet/index-085703.html
Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
I have now got the steps needed to call procedure from C#
//GIVE PROCEDURE NAME
cmd = new OracleCommand("PROCEDURE_NAME", con);
cmd.CommandType = CommandType.StoredProcedure;
//ASSIGN PARAMETERS TO BE PASSED
cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;
//THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;
//USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput);
//CALL PROCEDURE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
//RETURN VALUE
if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
{
//YOUR CODE
}
//OR
//IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
Hope this helps
It's basically the same mechanism as for a non query command with:
command.CommandText = the name of the
stored procedure
command.CommandType
= CommandType.StoredProcedure
As many calls to command.Parameters.Add as the number of parameters the sp requires
command.ExecuteNonQuery
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection
Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.
using (OracleConnection connection = new OracleConnection("ConnectionString"))
using (OracleCommand command = new OracleCommand("ProcName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
command.Parameters["return_out"].Direction = ParameterDirection.Output;
command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
command.Parameters["return_out2"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
}
This Code works well for me calling oracle stored procedure
Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.
using System.Data.OracleClient;
using System.Data;
then paste this code in event Handler
string str = "User ID=username;Password=password;Data Source=Test";
OracleConnection conn = new OracleConnection(str);
OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
cmd.CommandType = CommandType.StoredProcedure;
--Ad parameter list--
cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
....
conn.Open();
cmd.ExecuteNonQuery();
And its Done...Happy Coding with C#
In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:
using System.Data.OracleClient;
There are some system requirements here that you should verify are OK in your scenario.
Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.
Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);
Below worked for me in .NET Core solution. Note that it uses OracleDataReader and Oracle CommandType is CommandType.Text
using Oracle.ManagedDataAccess.Client;
.......
string spSql = "BEGIN STORED_PROC_NAME(:IN_PARAM, :OUT_PARAM1, :OUT_PARAM2); END; ";
using (OracleConnection oraCnn = new OracleConnection(cnnString))
using (OracleCommand oraCommand = new OracleCommand(spSql, oraCnn))
{
await oraCnn.OpenAsync(cancellationToken);
oraCommand.CommandType = CommandType.Text;
oraCommand.BindByName = true;
oraCommand.Parameters.Add("IN_PARAM", OracleDbType.Long, ParameterDirection.Input).Value = 123;
oraCommand.Parameters.Add("OUT_PARAM1", OracleDbType.Int32, null, ParameterDirection.Output);
oraCommand.Parameters.Add("OUT_PARAM2", OracleDbType.Varchar2, 4000, null, ParameterDirection.Output);
OracleDataReader objReader = oraCommand.ExecuteReader();
string outParamValue= oraCommand.Parameters["OUT_PARAM2"].Value.ToString();
}

how to fetch data using this coding

using this coding,while i give fruitId ,i need to retrieve fruitname,using this it shows some error..any one help...
string constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("savefruit11", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitsId", int.Parse(TextBox3.Text.Trim()));
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
}
}
Store procedure for the above code.
use[FruitsDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[savefruit11]
#FruitId INT,
#FruitName VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #FruitName = Fruitsname
FROM Fruits1
WHERE FruitsId = #FruitId
END
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
Your parameter is called #Fruitsname, but you get it back with #FruitName. You have an additional s in the first version. Make them consistent by changing the first #FruitsName to #FruitName which will match what you have in the stored procedure.
Or, as Henk suggested in the comments create a const string to contain your parameter name so that it is consistent across all usages.
Use cmd.ExecuteQuery or cmd.ExecuteScalar
//To Execute SELECT Statement
ExecuteQuery()
//To Execute Other Than Select Statement(means to Execute INSERT/UPDATE/DELETE)
ExecuteNonQuery()
with your udpate
s is missing in parameter name in stored procedure
Use the following example way
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.AdventureWorksData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = "HumanResources.uspUpdateEmployeePersonalInfo";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(
new SqlParameter("#EmployeeID", entity.EmployeeID));
command.Parameters.Add(
new SqlParameter("#NationalIDNumber", entity.NationalIDNumber));
command.Parameters.Add(
new SqlParameter("#BirthDate", entity.BirthDate));
command.Parameters.Add(
new SqlParameter("#MaritalStatus", entity.MaritalStatus));
command.Parameters.Add(
new SqlParameter("#Gender", entity.Gender));
connection.Open();
command.ExecuteNonQuery();
}
}
reference from MSDN
http://msdn.microsoft.com/en-us/library/jj635144.aspx

Accessing SQL Server stored procedure output parameter in C#

I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
#count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET #count=##ROWCOUNT;
RETURN
I am trying to access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["#count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.
Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.
Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery(); // *** since you don't need the returned data - just call ExecuteNonQuery
int ans = (int)cmd.Parameters["#count"].Value;
con.Close();
Console.WriteLine(ans);
}
Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:
ALTER PROCEDURE GetRowCount
AS
SELECT COUNT(*) FROM Emp WHERE age > 30;
and then use this snippet in your C# code:
con.Open();
object result = cmd.ExecuteScalar();
if(result != null)
{
int ans = Convert.ToInt32(result);
}
con.Close();
you have to specify that it is a stored procedure not a query
cmd.CommandType = CommandType.StoredProcedure;
Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case
cmd.ExecuteNonQuery();
Or if you want try with ExecuteScalar and ReturnValue
You should add
cmd.CommandType = CommandType.StoredProcedure
before calling it
I find the problem, its the connection string.
But now, in the code:
usuary = (string)cmd.Parameters["#USUARIO"].Value;
password = (string)cmd.Parameters["#CLAVE"].Value;
the compiler infomrs thats values are null...

Calling stored procedure with return value

I am trying to call a stored procedure from my C# windows application. The stored procedure is running on a local instance of SQL Server 2008. I am able to call the stored procedure but I am not able to retrieve the value back from the stored procedure. This stored procedure is supposed to return the next number in the sequence. I have done research online and all the sites I've seen have pointed to this solution working.
Stored procedure code:
ALTER procedure [dbo].[usp_GetNewSeqVal]
#SeqName nvarchar(255)
as
begin
declare #NewSeqVal int
set NOCOUNT ON
update AllSequences
set #NewSeqVal = CurrVal = CurrVal+Incr
where SeqName = #SeqName
if ##rowcount = 0 begin
print 'Sequence does not exist'
return
end
return #NewSeqVal
end
Code calling the stored procedure:
SqlConnection conn = new SqlConnection(getConnectionString());
conn.Open();
SqlCommand cmd = new SqlCommand(parameterStatement.getQuery(), conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param = cmd.Parameters.Add("#SeqName", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = "SeqName";
SqlDataReader reader = cmd.ExecuteReader();
I have also tried using a DataSet to retrieve the return value with the same result. What am I missing to get
the return value from my stored procedure? If more information is needed, please let me know.
You need to add a ReturnValue-direction parameter to the command:
using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = parameterStatement.getQuery();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");
// #ReturnVal could be any name
var returnParameter = cmd.Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
}
Setting the parameter's direction to ParameterDirection.ReturnValue instructs the SqlCommand to declare it as a variable and assign the stored procedure's return value to it (exec #ReturnValue = spMyProcedure...), exactly like you would write it in SQL.
I know this is old, but i stumbled on it with Google.
If you have a return value in your stored procedure say "Return 1" - not using output parameters.
You can do the following - "#RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD
cmd.ExecuteNonQuery();
rtn = (int)cmd.Parameters["#RETURN_VALUE"].Value;
The version of EnterpriseLibrary on my machine had other parameters.
This was working:
SqlParameter retval = new SqlParameter("#ReturnValue", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
db.ExecuteNonQuery(cmd);
object o = cmd.Parameters["#ReturnValue"].Value;
I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:
#Result int OUTPUT
And C#:
SqlParameter result = cmd.Parameters.Add(new SqlParameter("#Result", DbType.Int32));
result.Direction = ParameterDirection.ReturnValue;
In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.
r
Result.Direction = ParameterDirection.InputOutput;
This is a very short sample of returning a single value from a procedure:
SQL:
CREATE PROCEDURE [dbo].[MakeDouble] #InpVal int AS BEGIN
SELECT #InpVal * 2; RETURN 0;
END
C#-code:
int inpVal = 11;
string retVal = "?";
using (var sqlCon = new SqlConnection(
"Data Source = . ; Initial Catalog = SampleDb; Integrated Security = True;"))
{
sqlCon.Open();
retVal = new SqlCommand("Exec dbo.MakeDouble " + inpVal + ";",
sqlCon).ExecuteScalar().ToString();
sqlCon.Close();
}
Debug.Print(inpVal + " * 2 = " + retVal);
//> 11 * 2 = 22
ExecuteScalar(); will work, but an output parameter would be a superior solution.
You can try using an output parameter. http://msdn.microsoft.com/en-us/library/ms378108.aspx
Or if you're using EnterpriseLibrary rather than standard ADO.NET...
Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
db.ExecuteNonQuery(cmd);
var result = (int)cmd.Parameters["RetVal"].Value;
}
I see the other one is closed. So basically here's the rough of my code. I think you are missing the string cmd comment. For example if my store procedure is call:DBO.Test. I would need to write cmd="DBO.test". Then do command type equal to store procedure, and blah blah blah
Connection.open();
String cmd="DBO.test"; //the command
Sqlcommand mycommand;

Calling Oracle stored procedure from C#?

How does one call a stored procedure in oracle from C#?
Please visit this ODP site set up by oracle for Microsoft OracleClient Developers:
http://www.oracle.com/technetwork/topics/dotnet/index-085703.html
Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
I have now got the steps needed to call procedure from C#
//GIVE PROCEDURE NAME
cmd = new OracleCommand("PROCEDURE_NAME", con);
cmd.CommandType = CommandType.StoredProcedure;
//ASSIGN PARAMETERS TO BE PASSED
cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;
//THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;
//USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput);
//CALL PROCEDURE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
//RETURN VALUE
if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
{
//YOUR CODE
}
//OR
//IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
Hope this helps
It's basically the same mechanism as for a non query command with:
command.CommandText = the name of the
stored procedure
command.CommandType
= CommandType.StoredProcedure
As many calls to command.Parameters.Add as the number of parameters the sp requires
command.ExecuteNonQuery
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection
Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.
using (OracleConnection connection = new OracleConnection("ConnectionString"))
using (OracleCommand command = new OracleCommand("ProcName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
command.Parameters["return_out"].Direction = ParameterDirection.Output;
command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
command.Parameters["return_out2"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
}
This Code works well for me calling oracle stored procedure
Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.
using System.Data.OracleClient;
using System.Data;
then paste this code in event Handler
string str = "User ID=username;Password=password;Data Source=Test";
OracleConnection conn = new OracleConnection(str);
OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
cmd.CommandType = CommandType.StoredProcedure;
--Ad parameter list--
cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
....
conn.Open();
cmd.ExecuteNonQuery();
And its Done...Happy Coding with C#
In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:
using System.Data.OracleClient;
There are some system requirements here that you should verify are OK in your scenario.
Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.
Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);
Below worked for me in .NET Core solution. Note that it uses OracleDataReader and Oracle CommandType is CommandType.Text
using Oracle.ManagedDataAccess.Client;
.......
string spSql = "BEGIN STORED_PROC_NAME(:IN_PARAM, :OUT_PARAM1, :OUT_PARAM2); END; ";
using (OracleConnection oraCnn = new OracleConnection(cnnString))
using (OracleCommand oraCommand = new OracleCommand(spSql, oraCnn))
{
await oraCnn.OpenAsync(cancellationToken);
oraCommand.CommandType = CommandType.Text;
oraCommand.BindByName = true;
oraCommand.Parameters.Add("IN_PARAM", OracleDbType.Long, ParameterDirection.Input).Value = 123;
oraCommand.Parameters.Add("OUT_PARAM1", OracleDbType.Int32, null, ParameterDirection.Output);
oraCommand.Parameters.Add("OUT_PARAM2", OracleDbType.Varchar2, 4000, null, ParameterDirection.Output);
OracleDataReader objReader = oraCommand.ExecuteReader();
string outParamValue= oraCommand.Parameters["OUT_PARAM2"].Value.ToString();
}

Categories