C# how to call an as 400 stored procedure using oledb - c#

Hi I am trying to call an as400 stored procedure using OleDB. Could you please post an example of how to do it cause I've been following some tutorials but not matter what I do I always get an Invalid Token Exception
this is what I do
OleDbCommand sp = new OleDbCommand("CALL NASVARWG.SP001(?,?,?,?,?) ", connectionDB);
sp.CommandType = CommandType.StoredProcedure;
sp.Parameters.Add("P1", System.Data.OleDb.OleDbType.Char).Value = "ESANASTRIS";
sp.Parameters["P1"].Size = 10;
sp.Parameters["P1"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P2", System.Data.OleDb.OleDbType.Char).Value = "SAMNAS";
sp.Parameters["P2"].Size = 10;
sp.Parameters["P2"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P3", System.Data.OleDb.OleDbType.Char).Value = textBox_Reparto.Text;
sp.Parameters["P3"].Size = 6;
sp.Parameters["P3"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P4", System.Data.OleDb.OleDbType.Char).Value = "we can do this";
sp.Parameters["P4"].Size = 60;
sp.Parameters["P4"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P5", System.Data.OleDb.OleDbType.Char).Value = "help";
sp.Parameters["P5"].Size = 256;
sp.Parameters["P5"].Direction = ParameterDirection.Input;
sp.Prepare();
sp.ExecuteNonQuery();
the exception I get says "NASVARWG" is not a valid token. Why? that is the name of the library containing the procedure and the spelling is correct.
Thanks for your help

A C# code with CommandType.StoredProcedure example :
// assume a DB2Connection conn
DB2Transaction trans = conn.BeginTransaction();
DB2Command cmd = conn.CreateCommand();
String procName = "INOUT_PARAM";
cmd.Transaction = trans;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procName;
A C# code with CommandType.Text example :
// assume a DB2Connection conn
DB2Transaction trans = conn.BeginTransaction();
DB2Command cmd = conn.CreateCommand();
String procName = "INOUT_PARAM";
String procCall = "CALL INOUT_PARAM (#param1, #param2, #param3)";
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = procCall;
// Register input-output and output parameters for the DB2Command
cmd.Parameters.Add( new DB2Parameter("#param1", "Value1");
cmd.Parameters.Add( new DB2Parameter("#param2", "Value2");
DB2Parameter param3 = new DB2Parameter("#param3", IfxType.Integer);
param3.Direction = ParameterDirection.Output;
cmd.Parameters.Add( param3 );
// Call the stored procedure
Console.WriteLine(" Call stored procedure named " + procName);
cmd.ExecuteNonQuery();
// Register input-output and output parameters for the DB2Command
...
// Call the stored procedure
Console.WriteLine(" Call stored procedure named " + procName);
cmd.ExecuteNonQuery();

Related

Calling a PL_SQL function from inside c#

I have created a PL/SQL function and stored it in my oracle database.Now I want to call that function on clicking a button.
I am using visual studio and c#.
My humble attempt-
private void button3_Click(object sender, EventArgs e)
{
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
String x1 = textBox1.Text;
String x2 = textBox2.Text;
comm.CommandText = "log_in";
comm.Parameters.Add(new OracleParameter("c", OracleDbType.Varchar2, textBox1.Text, ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter("tt", OracleDbType.Varchar2, 256, ParameterDirection.ReturnValue));
String z = comm.Parameters["z"].Value.ToString();
comm.ExecuteNonQuery();
if (z.Equals('1'))
{ MessageBox.Show("correct"); }
conn.Close();
}
PL/SQL-
CREATE OR REPLACE FUNCTION log_in
(
x IN VARCHAR2,
y IN VARCHAR2
) RETURN VARCHAR2 AS
match_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO match_count
FROM student_login
WHERE email = x
AND password = y;
IF match_count = 0 THEN
RETURN 0;
ELSE
RETURN 1;
END IF;
END;
note-my data source is .NET framework data provider for oracle and the answer is for odp.net
Your function has two input parameters, thus your call must also define two input parameter plus the return parameter. Method Add(OracleParameter) is possible but redundant.
It should be like this:
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
comm.CommandText = "log_in";
comm.Parameters.Add("x", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox1.Text;
// As far as I remember "ParameterDirection.Input" is the default, so you may skip it
comm.Parameters.Add("y", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox2.Text;
comm.Parameters.Add("ret", OracleDbType.Byte, ParameterDirection.ReturnValue);
comm.Parameters["ret"].DbType = DbType.Byte;
comm.ExecuteNonQuery();
String returnValue = comm.Parameters["ret"].Value.ToString();
Actually I never used CommandType.StoredProcedure. If the code above does not work try this one instead:
comm.CommandType = CommandType.Text;
comm.CommandText = "BEGIN :ret := log_in(:x, :y); END;";
Hi I had some problems with StoredProcedure. And finally get it working.
comm = new OracleCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
comm.CommandText = "log_in";
// Important is to add returnValue as described bellow
OracleParameter retval = new OracleParameter("ret", OracleDbType.Varchar2 , 20);
retval.Direction = ParameterDirection.ReturnValue;
comm.Parameters.Add(retval);
comm.Parameters.Add("x", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox1.Text;
comm.Parameters.Add("y", OracleDbType.Varchar2, ParameterDirection.Input).Value = textBox2.Text;
comm.ExecuteNonQuery();
String returnValue = comm.Parameters["ret"].Value.ToString();

How can I get SQL Server stored procedure return value in c#?

I'm beginner in C# and SQL Server, and I wrote this query for creating a stored procedure in SQL Server:
create procedure newBehzad
#id bigint
as
DECLARE #ResultValue int
select *
from TABLEA
where id > #id
SET #ResultValue = -5
go
Everything is working, and I wrote this C# code to call that stored procedure and it return a single value:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("newBehzad", conn)
{
CommandType = CommandType.StoredProcedure
})
{
conn.Open();
command.Parameters.Add("#id", SqlDbType.BigInt).Value = 2;
command.Parameters.Add("#ResultValue", SqlDbType.Int);
SqlParameter retval = command.Parameters.Add("#ResultValue", SqlDbType.Int);
retval.Direction = ParameterDirection.ReturnValue;
retunvalue = (string)command.Parameters["#ResultValue"].Value;
//SqlParameter retval = sqlcomm.Parameters.Add("#b", SqlDbType.VarChar);
command.ExecuteNonQuery();
conn.Close();
}
MessageBox.Show(returnValue);
But when I run the C# windows application, I get this error:
Procedure or function newBehzad has too many arguments specified.
How can I solve that? Thanks.
Change you procedure to:
create procedure newBehzad #id bigint, #ResultValue int OUT
as
SET #ResultValue = 0
BEGIN
select *from TABLEA
where id>#id
SET #ResultValue = -5
END
go
Please try somethink like this:
object returnValue = null;
using (var conn = new System.Data.SqlClient.SqlConnection(AbaseDB.DBFactory.GetInstance().GetConnectionString()))
{
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("newBehzad", conn) { CommandType = CommandType.StoredProcedure })
{
conn.Open();
command.Parameters.Add("#id", SqlDbType.BigInt).Value = 2;
command.Parameters.Add("#ResultValue", SqlDbType.Int).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
returnValue = command.Parameters["#ResultValue"].Value;
conn.Close();
}
if (returnValue != null)
MessageBox.Show(returnValue.ToString());
}
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("newBehzad", conn)
{
CommandType = CommandType.StoredProcedure
})
{
conn.Open();
command.Parameters.Add("#id", SqlDbType.BigInt).Value = 2;
// command.Parameters.Add("#ResultValue", SqlDbType.Int); Comment this line
SqlParameter retval = command.Parameters.Add("#ResultValue", SqlDbType.Int);
retval.Direction = ParameterDirection.ReturnValue;
retunvalue = (string)command.Parameters["#ResultValue"].Value;
//SqlParameter retval = sqlcomm.Parameters.Add("#b", SqlDbType.VarChar);
command.ExecuteNonQuery();
conn.Close();
}
MessageBox.Show(returnValue);
First of all you need to change the stored proc to return the value:
create procedure newBehzad #id bigint
as
DECLARE #ResultValue int
select *from TABLEA
where id>#id
SET #ResultValue = -5
Return #ResultValue
go
Then grab it with:
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand("newBehzad", conn)
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter retval = new SqlParameter();
retval.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add("#id", SqlDbType.BigInt).Value = 2;
cmd.Parameters.Add(retval);
cmd.ExecuteNonQuery();
returnValue = (int)retval.Value;
}
}
But I really can not get why are you selecting data in the stored proc...

Return Value from a Stored Procedure

I am trying to get data returned from my stored procedure. This is what I have tried and absolutely nothing is coming back.
Stored Proc:
Declare #Submit_ID as int
Set #Submit_ID = (Select (Max(Sub_ID) + 1) from Sub_Details);
INSERT INTO.....
Return #Submit_ID
C# (2.0)
SqlConnection conn = null;
int subid;
try
{
conn = new SqlConnection(conn_string);
SqlCommand cmd = new SqlCommand("INSERT_INTO_MYDB", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("#FirstName", SqlDbType.NVarChar, 255);
p1.Direction = ParameterDirection.Input;
p1.Value = txtFirstName.Text;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("#LastName", SqlDbType.NVarChar, 255);
p2.Direction = ParameterDirection.Input;
p2.Value = txtLastName.Text;
cmd.Parameters.Add(p2);
SqlParameter pSub = new SqlParameter("#Sub_ID", SqlDbType.Int);
pSub.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
subid = Convert.ToInt32(pSub);
}
You're not adding the return parameter to the command:
SqlParameter pSub = new SqlParameter("#Sub_ID", SqlDbType.Int);
pSub.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(pSub); // <------------- add to command
conn.Open();
cmd.ExecuteNonQuery();
subid = Convert.ToInt32(cmd.Parameters["pSub"].Value);
First add parameter to cmd and use .Value to its value
cmd.Parameters.Add(pSub); // add parameters to command
cmd.ExecuteNonQuery();
subid = Convert.ToInt32(pSub.Value); // Use .Value

ORA-06550 wrong number or types of arguments when calling Oracle stored procedure

procedure select_card_transaction(trans_id nvarchar2,
usr_id number,
Quantity out number) is
begin
select count(*)
into Quantity
from user_cards u
where u.transaction_id = trans_id
and u.user_id = usr_id;
end;
and Consuming it:
using(var conn = new OracleConnection(Settings.Default.OraWUConnString))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "for_temporary_testing.select_card_transaction";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("trans_id", TransactionID);
cmd.Parameters.AddWithValue("usr_id", UserID);
var q = new OracleParameter("Quantity", OracleType.Number);
q.Direction = ParameterDirection.Output;
cmd.Parameters.Add(q);
//cmd.Parameters[0].OracleType = OracleType.NVarChar;
//cmd.Parameters[1].OracleType = OracleType.Number;
conn.Open();
var obj = cmd.ExecuteNonQuery();
conn.Close();
return (int)q.Value == 1;
}
It returns the following error.
ORA-06550 wrong number or types of arguments when calling Oracle stored procedure...
ANY IDEA?
I have had the same problem before. Are you using the ODP.Net drivers? I was able to solve the problem by adding the output parameter first. This needs to be done before the input parameters. In your case it would look like
using(var conn = new OracleConnection(Settings.Default.OraWUConnString))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "for_temporary_testing.select_card_transaction";
cmd.CommandType = CommandType.StoredProcedure;
// Return value parameter has to be added first !
var Quantity = new OracleParameter();
Quantity.Direction = ParameterDirection.ReturnValue;
Quantity.OracleDbType = OracleDbType.Int32;
cmd.Parameters.Add(Quantity);
//now add input parameters
var TransID = cmd.Parameters.Add("trans_id", TransactionID);
TransID.Direction = ParameterDirection.Input;
TransID.OracleDbType = OracleDbType.NVarchar2;
var UsrID = cmd.Parameters.Add("usr_id", UserID);
UsrID.Direction = ParameterDirection.Input;
UsrID.OracleDbType = OracleDbType.Int32;
cmd.ExecuteNonQuery();
conn.Close();
return Convert.ToInt32(Quantity.Value);
}
The problem was in the parameter. It was null and oracle returned error. I got that if argument is null, it should be sent as DBNULL

Trouble executing SQL stored procedure from C#

I have an existing stored procedure in SQL Server that I need to call from my C# code and get result. Here is how this SP looks like
CREATE PROCEDURE [dbo].[sp_MSnextID_DDB_NextID]
#tablesequence varchar(40)
AS
declare #next_id integer
begin transaction
update DDB_NextID
set DDB_SEQUENCE = DDB_SEQUENCE + 1
where DDB_TABLE = #tablesequence
select #next_id = DDB_SEQUENCE from DDB_NextID
where DDB_TABLE = #tablesequence
commit transaction
RETURN #next_id
Here is my C# code
using (OdbcConnection connection = new OdbcConnection(GetConnectionString()))
{
using (IDbCommand command = new OdbcCommand())
{
command.CommandText = "sp_MSnextID_DDB_NEXTID";
command.CommandType = CommandType.StoredProcedure;
IDbDataParameter parameter1 = command.CreateParameter();
parameter1.DbType = DbType.String;
parameter1.ParameterName = "#tablesequence";
parameter1.Value = "ddb_dc_document";
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
IDbDataParameter parameter2 = command.CreateParameter();
parameter2.DbType = DbType.Int32;
parameter2.ParameterName = "#Return_Value";
parameter2.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(parameter2);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
IDbDataParameter o = (command.Parameters)["#Return_Value"] as IDbDataParameter;
//Got return value from SP in o.Value
}
}
The trouble is I am getting exception
[42000] [Microsoft][SQL Native Client][SQL Server]Procedure or function 'sp_MSnextID_DDB_NextID' expects parameter '#tablesequence',
which was not supplied.
which I can't explain or fix. What I am missing?
To find a way around, I was trying different approach: executing the following query that sets data in a temp table
create table #temp (i integer); insert into #temp exec sp_MSNextID_DDB_NEXTID #tablesequence='ddb_dc_document';select * from #temp;
In this case SP is executed correctly but select returns zero rows!
Unfortunately, you can't use named parameters with OdbcCommand. You will need to instead execute a call statement to your stored procedure.
using (OdbcConnection connection = new OdbcConnection(GetConnectionString()))
{
using (IDbCommand command = new OdbcCommand())
{
command.CommandText = "{ ? = CALL sp_MSnextID_DDB_NEXTID(?) }";
command.CommandType = CommandType.StoredProcedure;
IDbDataParameter parameter2 = command.CreateParameter();
parameter2.DbType = DbType.Int32;
parameter2.ParameterName = "#Return_Value";
parameter2.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(parameter2);
IDbDataParameter parameter1 = command.CreateParameter();
parameter1.DbType = DbType.String;
parameter1.ParameterName = "#tablesequence";
parameter1.Value = "ddb_dc_document";
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
IDbDataParameter o = (command.Parameters)["#Return_Value"] as IDbDataParameter;
//Got return value from SP in o.Value
}
}
To make your workaround work you should replace
RETURN #next_id
in your procedure with
SELECT #next_id

Categories