oracle function always return null - c#

I'm using the flowing code to call the oracle function with the return value,
but it returns null always
OracleCommand cmd = new OracleCommand();
using (OracleConnection cnn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=321352427544)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=test)));User ID=abc;Password=123;"))
{
cmd.Connection = cnn;
cmd.CommandText = "GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("P_EMP_ID", OracleDbType.Int32).Value = 4241;
cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmd.ExecuteNonQuery();
string Count = (string)cmd.Parameters["return_value"].Value;
cnn.Close();
}

the problem was solved in two ways by
add cmd.BindByName = true;
add the return parameter in the first: cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;

Related

How to pass parameters in a oracle SQL query?

For the past few days I cannot pass any fixed parameters to my SQL query.
I try all possible tutorials to pass the parameter to a query, but nothing works.
However, I have seen by putting fixed parameters directly in the query (method 1) it worked perfectly.
I do not see that in method 2 prevents the functioning of my function.
When I say that it does not work is that in the first method my reader is filled while in the method 2 my reader is empty
method 1 : works (i don't need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet='demonstration'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
method 2 : doesn't works (I need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter("test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
String updateCmd;
SqlCommand myCommandUpd;
updateCmd = "UPDATE RHRMVacationRequest SET [EmplId] = #Emplid WHERE RecId = #RecId";
myCommandUpd = new SqlCommand(updateCmd, DataBase.GetConnetionToBase());
myCommandUpd.Parameters.Add(new SqlParameter("#Emplid", SqlDbType.VarChar, 10));
myCommandUpd.Parameters.Add(new SqlParameter("#RecId", SqlDbType.BigInt));
myCommandUpd.Parameters["#Emplid"].Value = emplIdUpd.Text.Trim();
myCommandUpd.Parameters["#RecId"].Value = Convert.ToInt64(RecIdUpd.Value.Trim());
myCommandUpd.Connection.Open();
myCommandUpd.ExecuteNonQuery();
may be i recall the wrong way round - maybe i tried :? and it did not work and used :test - but i think i got you issue, check the code below.
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter(":test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
After many hours of research, i have I finally found the solution:
public Boolean VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
string str = "demonstration";
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.BindByName = true;
cmd.CommandText = "select * from analyses where nom_projet='"+str+"'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Console.WriteLine("Data already exist");
return true;
}
Console.WriteLine("Data doesn't already exist");
return true;
}

Running Oracle Package: ORA-06550 || ORA-06502

When I try to run a package on our oracle database from Oracle's .net provider, or the Microsoft oracle provider, it gives me the following error:
{"ORA-06550: line 1, column 7:\nPLS-00221: 'BEGIN_TRANSACTION' is not a procedure or is undefined\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored"}
Here is my C# code:
OracleConnection cn = new OracleConnection(connectionString);
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
//cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Here is my package definition:
Function Begin_Transaction ( p_user_id IN NUMBER,
p_commt IN VARCHAR2
)
RETURN Number;
When I uncomment the third parameter that I've added, I get a different error:
{"ORA-06502: PL/SQL: numeric or value error: character to number conversion error\nORA-06512: at line 1"}
Try following code:
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add(new OracleParameter("p_user_id", OracleDbType.Decimal, 4720, ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter("p_commt", OracleDbType.Varchar2, "TEST", ParameterDirection.Input));
cmd.ExecuteNonQuery();
}
Comment:
Don't forgive wrap disposable objects in using construction.
I removed the username from the package definition, and also uncommented my add parameter for the return value.
using (OracleConnection cn = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();

How to Execute Update SQL Script in ASP.Net

I have this code to execute a stored procedure (Update SP) in ASP.Net, unfortunately record is not updating when I run the code.
This is my code:
using (SqlConnection sqlConnection = Connt.GetConnection(TblName))
{
sqlConnection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(SqlScript, sqlConnection))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.AddRange(SqlParam);
}
}
Where SqlScript is the variable for the stored procedure name and SqlParam is the parameters.
Please help me figure out what is wrong with my code.
Hi you can try something like this
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";
public void samplefunct(params object[] adparam)
{
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "SPName";
sqlCommand.Parameters.Add("#param1", SqlDbType.VarChar).Value = adparam[0];
sqlCommand.Parameters.Add("#param2", SqlDbType.VarChar).Value = adparam[1];
sqlCommand.Parameters.Add("#Param3", SqlDbType.VarChar).Value = adparam[2];
sqlCommand.ExecuteNonQuery();
}
Try:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
With a Param:
command.Parameters.Add(new SqlParameter("#ID", 123));

Getting error while supplying parameters to a stored procedure

I am getting the following error while supplying parameters to a stored procedure:
Procedure or function 'ismovieexists' expects parameter '#movie_name', which was not supplied
and the same error message for the procedure insert_values_in_movie_master..
public int add_movie(mymovie objmymovie)
{
SqlConnection cn = new SqlConnection(_connectionstring);
cn.Open();
//SqlDataReader dr;
SqlCommand cmd = new SqlCommand("ismovieexists", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#movie_name", objmymovie.MOVIE_NAME);
SqlParameter d = new SqlParameter("#d", SqlDbType.Int);
d.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(d);
cmd.ExecuteReader();
int i = (int)cmd.Parameters["#d"].Value;
if (i == 0)
{
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = cn;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "insert_values_in_movie_master";
cmd1.Parameters.AddWithValue("#movie_name", objmymovie.MOVIE_NAME);
cmd1.Parameters.AddWithValue("#rating", objmymovie.RATING);
cmd1.Parameters.AddWithValue("#realease_year", objmymovie.REALEASE_YEAR);
cmd1.Parameters.AddWithValue("#starcast", objmymovie.STARCAST);
cmd1.Parameters.AddWithValue("#language", objmymovie.LANGUAGE);
cmd1.Parameters.AddWithValue("#display_home", objmymovie.DISPLAY_HOME);
cmd1.Parameters.AddWithValue("#block_status", objmymovie.BLOCK_STATUS);
cmd1.Parameters.AddWithValue("#no_of_copies", objmymovie.no_of_copies);
cmd1.Parameters.AddWithValue("#MOVIE_category", objmymovie.MOVIE_category);
cmd1.Parameters.AddWithValue("#MOVIE_flag", objmymovie.MOVIE_FLAG);
cmd1.ExecuteNonQuery();
return i;
}
else
return 1;
}
Does the parameter #Movie_Name exist in your Stored Procedures? If the parameter does exist it's likely that you are not passing a value to objmymovie.MOVIE_NAME

Get output parameter value in ADO.NET

My stored procedure has an output parameter:
#ID INT OUT
How can I retrieve this using ado.net?
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["#ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["#Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from #Walter Stabosz and #Stephen Kennedy and to match the update code edit in the question from #abatishchev.
For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
SqlParameter outputParam = cmd.Parameters.Add("#ID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
conn.Open();
using(IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
//read in data
}
}
// reader is closed/disposed after exiting the using statement
int id = outputParam.Value;
}
Not my code, but a good example i think
source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
using System;
using System.Data;
using System.Data.SqlClient;
class OutputParams
{
[STAThread]
static void Main(string[] args)
{
using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
{
SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
cmd.CommandType=CommandType.StoredProcedure ;
SqlParameter parm= new SqlParameter("#CustomerID",SqlDbType.NChar) ;
parm.Value="ALFKI";
parm.Direction =ParameterDirection.Input ;
cmd.Parameters.Add(parm);
SqlParameter parm2= new SqlParameter("#ProductName",SqlDbType.VarChar);
parm2.Size=50;
parm2.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm2);
SqlParameter parm3=new SqlParameter("#Quantity",SqlDbType.Int);
parm3.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm3);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(cmd.Parameters["#ProductName"].Value);
Console.WriteLine(cmd.Parameters["#Quantity"].Value.ToString());
Console.ReadLine();
}
}
public static class SqlParameterExtensions
{
public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)
{
if (sqlParameter.Value == DBNull.Value
|| sqlParameter.Value == null)
{
if (typeof(T).IsValueType)
return (T)Activator.CreateInstance(typeof(T));
return (default(T));
}
return (T)sqlParameter.Value;
}
}
// Usage
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("storedProcedure", conn))
{
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
int result = outputIdParam.GetValueOrDefault<int>();
}
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“#Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“#Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“#Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “#EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
You can get your result by below code::
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add other parameters parameters
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#Id";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
conn.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string Id = outPutParameter.Value.ToString();
// *** read output parameter here, how?
conn.Close();
}
Create the SqlParamObject which would give you control to access methods on the parameters
:
SqlParameter param = new SqlParameter();
SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)
: param.ParameterName = "#yourParamterName";
Clear the value holder to hold you output data
: param.Value = 0;
Set the Direction of your Choice (In your case it should be Output)
: param.Direction = System.Data.ParameterDirection.Output;
That looks more explicit for me:
int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;

Categories

Resources