SQL error with Stored Procedure - c#

I am inserting rows in sql table through my c# code , which calls a Stored procedure .
C# code:
SqlCommand myCommand = thisConnection.CreateCommand();
myCommand.CommandText = "FederationUpdateCTRAndImpressionCountsForAllYPIds";
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#bid", SqlDbType.UniqueIdentifier);
myCommand.Parameters.Add("#uid", SqlDbType.UniqueIdentifier);
myCommand.Parameters.Add("#imp", SqlDbType.VarChar);
myCommand.Parameters.Add("#ctr", SqlDbType.VarChar);
while (myfederationReader.Read())
{
myCommand.Parameters["#bid"].Value = myfederationReader["BusinessId"];
myCommand.Parameters["#uid"].Value = myfederationReader["UId"];
myCommand.Parameters["#imp"].Value = myfederationReader["Impression"];
myCommand.Parameters["#ctr"].Value = myfederationReader["CTR"];
rowsAffected = myCommand.ExecuteNonQuery();
}
Stored proc:
CREATE PROCEDURE [dbo].[FederationUpdateCTRAndImpressionCountsForAllYPIds]
#bid uniqueidentifier,
#uid uniqueidentifier,
#imp varchar(255),
#ctr varchar(255)
AS BEGIN
UPDATE BasicBusinessInformation
SET BasicBusinessInformation.CTR = #ctr , BasicBusinessInformation.Impression = #imp
WHERE BasicBusinessInformation.BusinessId = #bid AND BasicBusinessInformation.UId = #uid
END
On executing it , following error is reported:
procedure has no parameters and arguments were supplied

Try clearing the Command parametres
[C#]
public bool ExportAndClear() {
SqlParameter[] myParamArray = new SqlParameter[myCmd.Parameters.Count - 1];
myCmd.Parameters.CopyTo(myParamArray, 0);
myCmd.Parameters.Clear();
return true;
}

try to fetch data from reader before you fire this command
like
1)Fetch data from reader and store in list or datatable
2)For loop on list or datatable
3)in for loop fire this command

Try moving the following
SqlCommand myCommand = thisConnection.CreateCommand();
myCommand.CommandText = "FederationUpdateCTRAndImpressionCountsForAllYPIds";
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#bid", SqlDbType.UniqueIdentifier);
myCommand.Parameters.Add("#uid", SqlDbType.UniqueIdentifier);
myCommand.Parameters.Add("#imp", SqlDbType.VarChar);
myCommand.Parameters.Add("#ctr", SqlDbType.VarChar);
In the while loop, see if you get different results.

Related

Call MySQL procedure with OUT parameter

I want to get the id of the last inserted row from mysql, but i get somekind of Exception unhandled. The visual studio gives me this error :
MySql.Data.MySqlClient.MySqlException: 'OUT or INOUT argument 9 for routine test.pr_VendegFelvetele is not a variable or NEW pseudo-variable in BEFORE trigger'.
mysql code:
CREATE PROCEDURE pr_VendegFelvetele(
IN uvezNev VARCHAR(75),
IN ukerNev VARCHAR(75),
IN uemail VARCHAR(255),
IN utel INT(15),
IN ucim VARCHAR(75),
IN uiranyito INT(5),
IN uvaros VARCHAR(55),
IN uorszag VARCHAR(45),
OUT uvendegID INT(11)
)
BEGIN
INSERT INTO `vendeg`(`vezNev`, `kerNev`, `email`, `tel`, `cim`, `iranyito`, `varos`, `orszag`)
VALUES (uvezNev, ukerNev, uemail, utel, ucim, uiranyito, uvaros, uorszag);
SET uvendegID = LAST_INSERT_ID();
END
By the way mysql procedure works perfectly.
c# code:
String query = "CALL pr_VendegFelvetele(#uvezNev, #ukerNev, #uemail, #utel, #ucim, #uiranyito, #uvaros, #uorszag, #uvendegID);";
MySqlCommand cmd = new MySqlCommand(query, Con);
cmd.Parameters.AddWithValue("#uvezNev", uvezNev);
cmd.Parameters["#uvezNev"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#ukerNev", ukerNev);
cmd.Parameters["#ukerNev"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#uemail", uemail);
cmd.Parameters["#uemail"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#utel", utel);
cmd.Parameters["#utel"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#ucim", ucim);
cmd.Parameters["#ucim"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#uiranyito", uiranyito);
cmd.Parameters["#uiranyito"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#uvaros", uvaros);
cmd.Parameters["#uvaros"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#uorszag", uorszag);
cmd.Parameters["#uorszag"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#uvendegID", MySqlDbType.Int32);
cmd.Parameters["#uvendegID"].Direction = ParameterDirection.Output;
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["#uvendegID"].Value.ToString());
I get it on cmd.ExecuteNonQuery();
I added these lines and now it works.
cmd.CommandText = "pr_VendegFelvetele";
cmd.CommandType = CommandType.StoredProcedure;
This link helped:
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-stored-using.html

Get Return Value from Stored procedure in asp.net

i have a stored procedure
ALTER PROC TESTLOGIN
#UserName varchar(50),
#password varchar(50)
As
Begin
declare #return int;
set #return = (SELECT COUNT(*)
FROM CPUser
WHERE UserName = #UserName
AND Password = #password);
return #return;
End
and in c#
SqlConnection con = db.con;
SqlCommand cmd = new SqlCommand("TESTLOGIN", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("#return", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(parm);
cmd.Parameters.Add(new SqlParameter("#UserName", txtUserName.Text.ToString().Trim()));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text.ToString().Trim()));
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(parm.Value);
but it always return 0. Please help me to solve this problem
You need a parameter with Direction set to ParameterDirection.ReturnValue in code but no need to add an extra parameter in SP. Try this
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int id = (int) returnParameter.Value;
2 things.
The query has to complete on sql server before the return value is sent.
The results have to be captured and then finish executing before
the return value gets to the object.
In English, finish the work and then retrieve the value.
this will not work:
cmm.ExecuteReader();
int i = (int) cmm.Parameters["#RETURN_VALUE"].Value;
This will work:
SqlDataReader reader = cmm.ExecuteReader();
reader.Close();
foreach (SqlParameter prm in cmd.Parameters)
{
Debug.WriteLine("");
Debug.WriteLine("Name " + prm.ParameterName);
Debug.WriteLine("Type " + prm.SqlDbType.ToString());
Debug.WriteLine("Size " + prm.Size.ToString());
Debug.WriteLine("Direction " + prm.Direction.ToString());
Debug.WriteLine("Value " + prm.Value);
}
if you are not sure
check the value of the parameter
before during and after the results have been processed by the reader.
you can try this.Add the parameter as output direction and after executing the query get the output parameter value.
SqlParameter parmOUT = new SqlParameter("#return", SqlDbType.Int);
parmOUT.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parmOUT);
cmd.ExecuteNonQuery();
int returnVALUE = (int)cmd.Parameters["#return"].Value;
Procedure never returns a value.You have to use a output parameter in store procedure.
ALTER PROC TESTLOGIN
#UserName varchar(50),
#password varchar(50)
#retvalue int output
as
Begin
declare #return int
set #return = (Select COUNT(*)
FROM CPUser
WHERE UserName = #UserName AND Password = #password)
set #retvalue=#return
End
Then you have to add a sqlparameter from c# whose parameter direction is out.
Hope this make sense.
If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure
I used the following stored procedure to return the value.
CREATE PROCEDURE usp_get_count
AS
BEGIN
DECLARE #VALUE int;
SET #VALUE=(SELECT COUNT(*) FROM tblCar);
RETURN #VALUE;
END
GO
Do it this way (make necessary changes in code)..
SqlConnection con = new SqlConnection(GetConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", username.Text);
SqlParameter p2 = new SqlParameter("password", password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
//do the things
}
else
{
lblinfo.Text = "abc";
}

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;

passing parameters to a stored procedure in C#

How can i send three parameters a to stored procedure in sql?
Here is my error: Procedure or function GetIslemIdleri has too many arguments specified.
This is my stored procedure:
CREATE PROCEDURE GetIslemDetayIdleri
#islemId int,
#dovizTanim nvarchar(10),
#yapilanIslemTuru nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
SELECT ([t0].[TOPLAMTUTAR]) + ([t0].[KDVTUTAR]) AS [value]
FROM [dbo].[TBLP1ISLEMDETAY] AS [t0]
INNER JOIN [dbo].[TBLP1ISLEM] AS [t1] ON [t1].[ID] = [t0].[ISLEM_ID]
WHERE ([t0].[ISLEM_ID] = #islemId) AND
([t0].[FIYATBIRIM] = #dovizTanim) AND
([t1].[YAPILANISLEM] = #yapilanIslemTuru) AND
([t0].[KDVDAHILMI] = 0)
END
Here is my code:
decimal kurToplamQuery = 0;
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer1"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(connString);
sqlConn.Open();
SqlCommand cmd;
cmd = new SqlCommand("GetIslemIdleri", sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#islemId", SqlDbType.Int)).Value = islemId;
cmd.Parameters.Add(new SqlParameter("#dovizTanim", SqlDbType.NVarChar)).Value = dovizTanim;
cmd.Parameters.Add(new SqlParameter("#yapilanIslemTuru", SqlDbType.NVarChar)).Value = yapilanIslemTipi;
using (var reader = cmd.ExecuteReader())*//error occurs here*
{
while (reader.Read())
{
kurToplamQuery = reader.GetDecimal(0);
}
}
sqlConn.Close();
return kurToplamQuery;
Thanks for your helps.
The stored procedure is called GetIslemDetayIdleri but the code is using a stored procedure called GetIslemIdleri. Maybe the latter has fewer parameters than the former and you meant to call the former in the code?
Your stored procedure: GetIslemDetayIdleri have different name then your invocation:
cmd = new SqlCommand("GetIslemIdleri", sqlConn);
GetIslemDetayIdleri != GetIslemIdleri
in my case this code is worked .i hope this will work for your case
Procedure parameter names , type and lenght must be same
like that
cmd.Parameters.Add(new SqlParameter("#islemId", SqlDbType.Int)).Value = islemId;
cmd.Parameters.Add(new SqlParameter("#dovizTanim", SqlDbType.NVarChar ,10)).Value = dovizTanim;
cmd.Parameters.Add(new SqlParameter("#yapilanIslemTuru", SqlDbType.NVarChar,20)).Value = yapilanIslemTipi;

How to pass value to a stored procedure using C#

--Stored procedure
ALTER PROCEDURE [dbo].[Test]
#USERID varchar(25)
AS
BEGIN
SET NOCOUNT ON
IF NOT EXISTS Select * from Users where USERID = #USERID)
BEGIN
INSERT INTO Users (USERID,HOURS) Values(#USERID, 0);
END
I have this stored procedure in sql server 2005 and want to pass userid from a C# application. How can I do that. Many Thanks.
This topic is extensively covered in MSDN here. See the section entitled "Using Parameters with a SqlCommand and a Stored Procedure" for a nice sample:
static void GetSalesByCategory(string connectionString,
string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory";
command.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}

Categories