I need to execute a stored procedure in C# code, but I get an error that there are too many arguments.
Here is the code:
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
SqlCommand command = new SqlCommand("Cargar_VentasCajero", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter paramCodRetorno = new SqlParameter("hola", SqlDbType.Int);
paramCodRetorno.Direction = ParameterDirection.Output;
command.Parameters.Add(paramCodRetorno);
command.CommandTimeout = 16000;
DateTime Inicio1 = DateTime.Now.AddDays(-1);
DateTime fin1 = DateTime.Now;
command.Parameters.AddWithValue("#FECHAINICIAL", Inicio1);
command.Parameters.AddWithValue("#FECHAFINAL", fin1);
command.ExecuteNonQuery();
return Convert.ToInt32(command.Parameters["CodRetorno"].Value);
}
and this is the stored procedure:
ALTER PROCEDURE [dbo].[Cargar_VentasCajero]
#FECHAINICIAL VARCHAR(50),
#FECHAFINAL VARCHAR(50)
AS
DELETE FROM ventasxCajero
WHERE Fecha BETWEEN #FECHAINICIAL AND #FECHAFINAL
INSERT INTO ventasxcajero
SELECT
Fecha, Id_Sucursal,
SUM(CAST(Venta_Neta AS float)) AS 'Venta Neta',
SUM(CAST(Venta_Neta AS float)) - SUM(CAST(Iva AS float)) AS 'Venta Neta sin IVA',
Identificacion_Cajero,
COUNT(*) AS 'Transacciones'
FROM
VentasConConvenios vc
INNER JOIN
speedyanalitica.dbo.Afiliados Af ON Af.TipDocumento + '-' + Af.NumeroDocumento = vc.Id_Cliente
WHERE
Fecha BETWEEN #FECHAINICIAL AND #FECHAFINAL
AND Id_Sucursal LIKE 'S%'
AND ((vc.DesTipoVenta = 'Venta Comercial') OR
(vc.DesTipoVenta = 'Venta Convenios'))
AND vc.DesTipoProducto = 'Venta'
GROUP BY
Fecha, Id_Sucursal, Identificacion_Cajero
SELECT *
FROM ventasxCajero
WHERE Fecha BETWEEN #FECHAINICIAL AND #FECHAFINAL
I tried to run it, it enters the database and everything, but the only problem is that it doesn't want to run the stored procedure due to argument problems.
Related
I'm trying to call a stored procedure to make an insert:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=******;Initial Catalog=**********;Integrated Security=True";
using (SqlConnection sqlCon = new SqlConnection(connectionString: connectionString))
{
using (SqlCommand cmd = new SqlCommand("InsertAngajat", sqlCon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Nume", SqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#Prenume", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.Add("#DataNasterii", SqlDbType.Date).Value = textBox4.Text;
cmd.Parameters.Add("#DataAngajare", SqlDbType.Date).Value = DateTime.Today.ToString();
cmd.Parameters.Add("#cnp", SqlDbType.Char).Value = textBox3.Text.ToCharArray();
cmd.Parameters.Add("#Localitate", SqlDbType.VarChar).Value = textBox8.Text;
cmd.Parameters.Add("#Judet", SqlDbType.VarChar).Value = textBox10.Text;
cmd.Parameters.Add("#Strada", SqlDbType.VarChar).Value = textBox9.Text;
cmd.Parameters.Add("#Departament", SqlDbType.VarChar).Value = comboBox1.Text;
cmd.Parameters.Add("#Telefon", SqlDbType.Char).Value = textBox5.Text.ToCharArray();
if (checkBox1.Checked)
cmd.Parameters.Add("#Sex", SqlDbType.Char).Value = 'M';
else if (checkBox2.Checked)
cmd.Parameters.Add("#Sex", SqlDbType.Char).Value = 'F';
else
MessageBox.Show("Nu a fost bifat sexul");
cmd.Parameters.Add("#Numar", SqlDbType.Int).Value = Convert.ToInt32(textBox11.Text);
cmd.Parameters.Add("#Salariu", SqlDbType.Int).Value = Convert.ToInt32(textBox6.Text);
sqlCon.Open();
cmd.ExecuteNonQuery();
}
}
this.Close();
}
But this is the error I get when I press the button and save everything.
https://i.imgur.com/0tixhsu.png
This is the SQL Server stored procedure:
ALTER PROCEDURE [dbo].[InsertAngajat]
#Nume VARCHAR(50),
#Prenume VARCHAR(50),
#Departament VARCHAR(50),
#cnp CHAR(13),
#DataNasterii DATE,
#Telefon VARCHAR(12) = "NONE",
#DataAngajare DATE,
#Salariu INT,
#Sex CHAR(1) = 'F',
#Judet VARCHAR(50),
#Localitate VARCHAR(50),
#Strada VARCHAR(50),
#Numar INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #DepID INT = (SELECT D.DepartamentID
FROM Departamente D
WHERE D.[Nume Departament] = #Departament);
INSERT INTO [dbo].Angajat (Nume, Prenume, DepartamentID, CNP, DataNasterii,
Telefon, DataAngajarii, Salariu, Sex, Localitate,
[Sector/Judet], Strada, nr)
VALUES (#Nume, #Prenume, #DepID, #cnp, #DataNasterii,
#Telefon, #DataAngajare, #Salariu, #Sex, #Localitate,
#Judet, #Strada, #Numar)
END
I made sure that the text boxes were having data. I have no idea what else to try.
I'm expecting that as long as the values in the text boxes aren't NULL to be able to Insert all their data easily.
It seems to me that your issue probably lies with this line:
Declare #DepID int = (Select D.DepartamentID From Departamente D Where D.[Nume Departament] = #Departament);
What happens if there are no results for this query? I'm a bit rusty, but I imagine #DepId will be NULL. Then when you try and insert it into your table, you're inserting a null.
Solution: Either in your procedure, or before calling the insert, check if the department exists.
Run your sql profiler and trace the call. So that, you will be sure about your all input parameters. And then execute your procedure call manually. You will be able to find the exact issue and the line in the procedure. Try one with fixed value of #DepID int=1. If it's running successfully. Then you have to optimized this line of code as below:
Declare #DepID int = (Select isnull(D.DepartamentID,0) From Departamente D Where D.[Nume Departament] = #Departament);
It seems your Departamente table don't have data for this department.
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.
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";
}
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;
I have a stored procedure, which returns the unique identifier after insertion ##identity. I tried it in the server explorer and it works as expected #RETURN_VALUE = [identifier].
In my code I added a parameter called #RETURN_VALUE, with ReturnValue direction first, than any other parameters, but when I run my query with ExecuteNonQuery() that parameter remains empty. I don't know what I've done wrong.
Stored Procedure
ALTER PROCEDURE dbo.SetAuction
(
#auctionID int,
#itemID int,
#auctionType tinyint,
#reservationPrice int,
#maxPrice int,
#auctionEnd datetime,
#auctionStart datetime,
#auctionTTL tinyint,
#itemName nchar(50),
#itemDescription nvarchar(MAX),
#categoryID tinyint,
#categoryName nchar(50)
) AS
IF #auctionID <> 0
BEGIN
BEGIN TRAN T1
UPDATE Auction
SET AuctionType = #auctionType,
ReservationPrice = #reservationPrice,
MaxPrice = #maxPrice,
AuctionEnd = #auctionEnd,
AuctionStart = #auctionStart,
AuctionTTL = #auctionTTL
WHERE AuctionID = #auctionID;
UPDATE Item
SET
ItemName = #itemName,
ItemDescription = #itemDescription
WHERE
ItemID = (SELECT ItemID FROM Auction WHERE AuctionID = #auctionID);
COMMIT TRAN T1
RETURN #auctionID
END
ELSE
BEGIN
BEGIN TRAN T1
INSERT INTO Item(ItemName, ItemDescription, CategoryID)
VALUES(#itemName, #itemDescription, #categoryID);
INSERT INTO Auction(ItemID, AuctionType, ReservationPrice, MaxPrice, AuctionEnd, AuctionStart, AuctionTTL)
VALUES(##IDENTITY,#auctionType,#reservationPrice,#maxPrice,#auctionEnd,#auctionStart,#auctionTTL);
COMMIT TRAN T1
RETURN ##IDENTITY
END
C# Code
cmd.CommandText = cmdText;
SqlParameter retval = new SqlParameter("#RETURN_VALUE", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
cmd.Parameters.AddRange(parameters);
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#RETURN_VALUE"].Value;
Just tried on my box and this works for me:
In SQL Server:
DROP PROCEDURE TestProc;
GO
CREATE PROCEDURE TestProc
AS
RETURN 123;
GO
In C#
string cnStr = "Server=.;Database=Sandbox;Integrated Security=sspi;";
using (SqlConnection cn = new SqlConnection(cnStr)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand("TestProc", cn)) {
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnValue = new SqlParameter();
returnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValue);
cmd.ExecuteNonQuery();
Assert.AreEqual(123, (int)returnValue.Value);
}
}
I solved the problem:
you have to set SqlCommand.CommandType to CommandType.StoredProcedure in order to get return values and/or output parameters. I haven't found any documentation about that, but now everything works.
Do you get the value of you EXEC in TSQL? I wonder if refactoring the TSQL would help (and using SCOPE_IDENTITY():
so change:
COMMIT TRAN T1
RETURN ##IDENTITY
to:
SET #auctionID = SCOPE_IDENTITY()
COMMIT TRAN T1
RETURN #auctionID
(I would also change the other ##IDENTITY to SCOPE_IDENTITY())
As a minor optimisation, you could also use:
return (int)retval.Value;
but this side of things should have worked "as is" from what I can see (hence why I'm focusing on the TSQL).
Some one can also use this simple and short method to calculate return value from SP
In SQL:
Create Table TestTable
(
Int Id
)
CREATE PROCEDURE Proc_TestProc
#Id
AS
Begin
Set NOCOUNT ON //Use this line if you don't want to return any message from SQL
Delete from TestTable where Id = #Id
return 1
Set NOCOUNT OFF //NOCOUNT OFF is Optional for NOCOUNT ON property
End
Sql Server always returns Int type value only.
and in C#
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TestConnectionString"].ToString()))
using (SqlCommand cmd = new SqlCommand("Proc_TestProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", 1);
var returnParameter = cmd.Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
}
You can also check your return value in SQL by using this command:
DECLARE #return_status int;
EXEC #return_status = dbo.[Proc_TestProc] 1;
SELECT 'Return Status' = #return_status;
print 'Returned value from Procedure: ' + Convert(varchar, #return_status); // Either previous or this line both will show you the value of returned value
you can use standart ways that you use before in normal queries but in Sql command you must write EXEC before your store procedure name and dont use commandtype like this :
SqlConnection con = new SqlConnection(["ConnectionString"])
SqlCommand com = new SqlCommand("EXEC _Proc #id",con);
com.Parameters.AddWithValue("#id",["IDVALUE"]);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
ArrayList liste = new ArrayList();
While(rdr.Read())
{
liste.Add(rdr[0]); //if it returns multiple you can add them another arrays=> liste1.Add(rdr[1]) ..
}
con.Close();