Parameter must be declared during executeNonQuery in Connector.NET using mySql - c#

I'm using MySqlConnector to execute query in C# code.
I have example procedure:
CREATE PROCEDURE RC_TEST
(
ZIPCODE VARCHAR(7),
INOUT SEARCH_VALUE VARCHAR(2)
)
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SET #SWV_Error = 1;
END;
SELECT TB_TABLE.SEARCH_VALUE INTO SEARCH_VALUE FROM TB_TABLE
WHERE TB_TABLE.ZIPCODE = ZIPCODE;
IF #SWV_ERROR <> 0 THEN
SET SEARCH_VALUE = NULL
END IF;
END;
When I'm executing this procedure in MySql Workbench - everything is ok.
But when I'm the same piece of code execute in C# code:
conn.Open();
var command = new MySqlCommand(script, conn);
command.ExecuteNonQuery();
conn.Close();
I got the error:
"Parameter '#SWV_Error' must be defined."
What am I doing wrong?

Related

Error - stored procedure has no parameters and arguments were supplied in c#

When I'm trying to call store procedure and return the value from the procedure, I'm getting the error message - procedure has no parameters and arguments were supplied
Below is the c# code:
using (SqlCommand command2 = new SqlCommand("getservername8", conn1))
{
command2.CommandType = CommandType.StoredProcedure;
command2.Parameters.Add("#s", SqlDbType.NVarChar, 500);
command2.Parameters["#s"].Direction = ParameterDirection.Output;
command2.ExecuteNonQuery();
string server = (string)command2.Parameters["#s"].Value;
}
Below is the stored procedure:
GO
ALTER procedure [dbo].[getservername9]
#s varchar(50)
as begin
declare #server_name varchar(500)
select #server_name = short_description from [Event_alerts].[dbo].[event_alerts]
select #s= SUBSTRING(#server_name, CHARINDEX('-', #server_name) + 15, 50)
return #s
end
Stored procedure gets executed with no error.Any help will be much appreciated
Use ExecuteScalar instead of Executenonquery. Please refer..
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-3.1
Please make below changes to your code -
Mark your variable in the stored procedure as output like below -
#s varchar(50) output
You cannot return varchar output values like you added in stored procedure.
Stored procedures always return integer values when you use return
statement here. In your case you will get below error when executed -
(the same can be observed in .NET end as well).
declare #s varchar(50)
exec [dbo].[getservername9] #s
Conversion failed when converting the varchar value '' to data
type int.
Remove the return statement from stored procedure which will automatically return the value back to .NET code.
Finally make the stored procedure names consistent in both .NET and SQL procedure.
First is to change your store procedure name, in the code you are using getservername8 while your stored procedure name is getservername9, the second point you need to mark your parameter as output as show in the code below
Code :
using (SqlCommand command2 = new SqlCommand("getservername", conn1))
{
command2.CommandType = CommandType.StoredProcedure;
command2.Parameters.Add("#s", SqlDbType.NVarChar, 500);
command2.Parameters["#s"].Direction = ParameterDirection.Output;
command2.ExecuteNonQuery();
string server = (string)command2.Parameters["#s"].Value;
}
Stored Procedure :
GO
ALTER procedure [dbo].[getservername]
#s varchar(50) output
as begin
declare #server_name varchar(500)
select #server_name = short_description from [Event_alerts].[dbo].[event_alerts]
select #s= SUBSTRING(#server_name, CHARINDEX('-', #server_name) + 15, 50)
return #s
end

Stored procedure Output parameter in c# is returning Empty where as Working fine while Excecuting in SQL

I have created a stored procedure where I have a declared an output parameter. It is giving correct result when I execute it in SQL. but I intergrated it in c# code I am getting an Empty object.I am not sure what is the problem.
I have visited so many links but didn't find any appropriate answer.
Here is my C# function Code :-
public bool PreviewAsReviewerButtonEnableDisable(string advId, string userType)
{
bool result = false;
using (RMS_MVCEntities entities = new RMS_MVCEntities())
{
var command = entities.Database.Connection.CreateCommand();
command.CommandText = "[AdvTax].[usp_PreviewAsReviewerButton_Enable_Disable]";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#AdvID", advId));
command.Parameters.Add(new SqlParameter("#Type", userType));
command.Parameters.Add(new SqlParameter("#EnableDisable", SqlDbType.Bit));
command.Parameters["#EnableDisable"].Direction = ParameterDirection.Output;
entities.Database.Connection.Open();
var reader = command.ExecuteReader();
result = Convert.ToBoolean(command.Parameters["#EnableDisable"].Value);
entities.Database.Connection.Close();
}
return result;
}
Here is my Sql Stored Procedure :-
ALTER PROCEDURE [AdvTax].[usp_PreviewAsReviewerButton_Enable_Disable]
#AdvID nvarchar(20),
#Type nvarchar(20),
#EnableDisable bit output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
If #Type='CTT Maker'
Begin
Declare #Count int=(select Count(*) from [AdvTax].[AdvTax_Computation] where AdvID=#AdvID and IsActive=1)
If #Count>0
Begin
set #EnableDisable=1
End
Else
Begin
set #EnableDisable=0
End
End
If #Type='CTT Checker'
Begin
Declare #Count1 int=(select Count(*) from [AdvTax].[AdvTax_Computation_Checker]
where AdvID=#AdvID and IsActive=1)
If #Count1>0
Begin
set #EnableDisable=1
End
Else
Begin
set #EnableDisable=0
End
End
END
Kindly help.
You can try to assign it directly
var result = (bool)command.ExecuteReader();
Hope this helps.

Run MySQL DDL command using C# Application

I am using MySQL database with C# to develop an application.Using MySQL Server 5.0 and odbc connector.
In some cases I am required to execute ddl commands such as ALTER TABLE or CREATE TABLE to manipulate the database. In these cases I need to use the IF EXISTS command to check the database before I execute commands. I write below commands that execute without any problem in Navicat or Workbench, but do not work when send this commands with application by ExecuteNoneQury methods.
what is wrong?
use db;
drop procedure if exists sp_update ;
delimiter //
create procedure sp_update()
begin
if not exists( SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tab' AND COLUMN_NAME = 'col' and table_schema = 'db') then
ALTER TABLE `tab` ADD COLUMN `col` int(11) NULL DEFAULT NULL ;
end if;
end//
delimiter ;
call sp_update();
drop procedure if exists sp_update ;
C# Command :
public override int ExecuteNoneQuery(string commandText)
{
int obTemp = 0;
Conn = new MySqlConnection(Connection.ConnectionString);
try
{
MySqlCommand MySqlCommand = new MySqlCommand(commandText, Conn);
if (Conn.State == ConnectionState.Closed)
{
Conn.Open();
}
obTemp = MySqlCommand.ExecuteNonQuery();
}
finally
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
return obTemp;
}
"delimiter" is not MySQL syntax.. It is a convinience function for the mysql command line client and is only understood by it (well, some GUI clients mimic the behavior too, to be able to run scripts that are originally thought for command line client).
But, you do not need "delimiter" in any code executed by connectors. Using it will result in syntax error like the one you got.
I solved my own problem. I needed to split up my sql command into two parts.
Part 1 create procedure:
drop procedure if exists sp_update ;
create procedure sp_update()
begin
if not exists( SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tab' AND COLUMN_NAME = 'col' and table_schema = 'db') then
ALTER TABLE `tab` ADD COLUMN `col` int(11) NULL DEFAULT NULL ;
end if;
end
Part 2:
call sp_update();
drop procedure if exists sp_update ;
Send each command to MySQL separately.

ODP .NET Getting a SYSREFCURSOR output. {"Unsupported column datatype"} error

I am trying to execute a procedure that returns a stored procedure. My version of Oracle DB is 9.2 and the ODP .NET version is 10.2.0.100
My C# code looks like this.
OracleCommand od = new OracleCommand();
od.Connection = oc;
OracleParameter opBranchNo;
OracleParameter opSysRef;
od.CommandType = System.Data.CommandType.StoredProcedure;
od.CommandText = "pkg_fetchleaseinfo.proc_fetchleaseheader";
opBranchNo = new OracleParameter("IBRANCH_ID", OracleDbType.Varchar2, 3, "044");
opBranchNo.Direction = System.Data.ParameterDirection.Input;
od.Parameters.Add(opBranchNo);
opSysRef = new OracleParameter();
opSysRef.ParameterName = "REC_SET";
opSysRef.Direction = System.Data.ParameterDirection.Output;
opSysRef.OracleDbType = OracleDbType.RefCursor;
od.Parameters.Add(opSysRef);
od.Prepare();
od.ExecuteNonQuery();
Oracle.DataAccess.Types.OracleRefCursor sysref =
(Oracle.DataAccess.Types.OracleRefCursor)opSysRef.Value;
return sysref.GetDataReader();
//OracleDataReader dr1 =
//((Oracle.DataAccess.Types.OracleRefCursor)opSysRef.Value).GetDataReader();
//return dr1;
My Oracle Procedure code looks like this
PROCEDURE proc_fetchleaseheader(ibranch_id IN VARCHAR2,
rec_set OUT SYS_REFCURSOR) IS x_rec genericCursor;
BEGIN
OPEN x_rec FOR SELECT getleaseheaderrows(ibranch_id) FROM dual;
rec_set := x_rec;
EXCEPTION WHEN OTHERS THEN
RAISE;
END;
When I execute my code, the part where I attempt a GetReader() fails with an UNSUPPORTED COLUMN DATATYPE error message.
I believe you are opening a refCursor to hold a Select [RefCursor] from dual
why don't you just
PROCEDURE proc_fetchleaseheader(ibranch_id IN VARCHAR2,
rec_set OUT SYS_REFCURSOR) IS x_rec genericCursor;
BEGIN
x_rec := getleaseheaderrows(ibranch_id);
rec_set := x_rec;
/**EXCEPTION WHEN OTHERS THEN --no need for this, the proc will raise just fine without being explicitly told to do so
RAISE;
***/
END;
or better yet just call getleaseheaderrows from the .net side and drop the procedure (just remember for parameters in ODP it always expects the function return value as the first param.

OdbcCommand on Stored Procedure - "Parameter not supplied" error on Output parameter

I'm trying to execute a stored procedure (against SQL Server 2005 through the ODBC driver) and I recieve the following error:
Procedure or Function 'GetNodeID' expects parameter '#ID', which was not supplied.
#ID is the OUTPUT parameter for my procedure, there is an input #machine which is specified and is set to null in the stored procedure:
ALTER PROCEDURE [dbo].[GetNodeID]
#machine nvarchar(32) = null,
#ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM Nodes WHERE NodeName=#machine)
BEGIN
SELECT #ID = (SELECT NodeID FROM Nodes WHERE NodeName=#machine)
END
ELSE
BEGIN
INSERT INTO Nodes (NodeName) VALUES (#machine)
SELECT #ID = (SELECT NodeID FROM Nodes WHERE NodeName=#machine)
END
END
The following is the code I'm using to set the parameters and call the procedure:
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#machine", OdbcType.NVarChar);
Cmd.Parameters["#machine"].Value = Environment.MachineName.ToLower();
Cmd.Parameters.Add("#ID", OdbcType.Int);
Cmd.Parameters["#ID"].Direction = ParameterDirection.Output;
Cmd.ExecuteNonQuery();
_NodeID = (int)Cmd.Parameters["#Count"].Value;
I've also tried using Cmd.ExecuteScalar with no success. If I break before I execute the command, I can see that #machine has a value.
If I execute the procedure directly from Management Studio, it works correctly.
Any thoughts? Thanks
Try replacing :
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
With :
OdbcCommand Cmd = new OdbcCommand("{call GetNodeID(?,?)}", _Connection);
More info :
http://support.microsoft.com/kb/310130
I'm not exactly sure what you mean by
there is an input #machine which is
specified and is set to null in the
stored procedure
In your proc's signature, this line:
#machine nvarchar(32) = null
doesn't mean that you're setting #machine to null inside the proc - it means you're assigning a default value to be used in case the parameter is missing (in this case, null is the value to be used for a missing param).
Getting the error about #ID being missing would happen if you were calling this stored procedure without passing any parameters at all (#machine would not be flagged as a problem since it has a default value defined). Your code example looks fine to me - are you sure the stored proc isn't being called from somewhere else in your program (somewhere where no parameters are being added)?
Stored procedure with input parameters and ODBC Connection:
create a stored procedure:
create procedure proc_name #parm1 varchar(20), #parm2 varchar(10) as begin insert into table_name values(#parm1,#parm2);end
This code works in SQL Server.
private void button1_Click(object sender, EventArgs e)
{
string name = txtname.Text;
string num = txtnum.Text;
OdbcConnection con = new OdbcConnection("dsn=naveenk_m5");
OdbcCommand cmd = new OdbcCommand("{call proc1(?,?)}",con);
cmd.Parameters.Add("#parm1", OdbcType.VarChar).Value=name;
cmd.Parameters.Add("#parm2", OdbcType.VarChar).Value = num;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("inserted a row");
}

Categories

Resources