Procedure or function xxxxx has too many arguments specified [duplicate] - c#

This question already has answers here:
Procedure or function !!! has too many arguments specified
(8 answers)
Closed 4 years ago.
My stored procedure is as follows :
ALTER PROCEDURE [dbo].[sp5]
#mat NVARCHAR(1000) = NULL,
#party NVARCHAR(1000) = NULL,
#place NVARCHAR(1000) = NULL,
#truk NVARCHAR(1000) = NULL,
#qty NVARCHAR(10) = NULL,
#ptm NVARCHAR(10) = NULL,
#mop NVARCHAR(100) = NULL,
#tos NVARCHAR(100) = NULL,
#driver NVARCHAR(100) = NULL,
#date1 DATE = NULL
AS
BEGIN
DECLARE #sql NVARCHAR(4000);
DECLARE #params NVARCHAR(4000);
DECLARE #rate nvarchar(10);
SET #sql ='select #rate = ['+#mat+'] from tblcos'+ ' where [Name] = #party'
set #params = '#party nvarchar (1000), #rate NVARCHAR(10) OUTPUT'
exec sp_executesql #sql, #params,#party= #party,#rate = #rate OUTPUT
INSERT INTO tblsls([Party], [Place], [truk], [Material], [Qty], rate,
[Payment], [MOP], [TOS], [driver], [Date])
SELECT
#party, #place, #truk, #mat, #qty, #rate,
#ptm, #mop, #tos, #driver, #date1
END
aspx.cs code file is as follows :
namespace crusoft
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["VRAConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("sp5", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#date1", SqlDbType.Date).Value = Calendar1.SelectedDate.ToShortDateString();
cmd.Parameters.AddWithValue("#party", SqlDbType.NVarChar).Value = Ddprt.SelectedValue;
cmd.Parameters.AddWithValue("#place", SqlDbType.NVarChar).Value = tbpls.Text;
cmd.Parameters.AddWithValue("#truk", SqlDbType.NVarChar).Value = Tbtru.Text;
cmd.Parameters.AddWithValue("#mat", SqlDbType.NVarChar).Value = Ddmat.SelectedValue;
cmd.Parameters.AddWithValue("#qty", SqlDbType.SmallInt).Value = Tbqty.Text;
cmd.Parameters.Add("#rate", SqlDbType.NVarChar, 10);
cmd.Parameters["#rate"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#ptm", SqlDbType.NVarChar).Value = Tbptm.Text;
cmd.Parameters.AddWithValue("#mop", SqlDbType.NVarChar).Value = Ddmop.SelectedValue;
cmd.Parameters.AddWithValue("#tos", SqlDbType.NVarChar).Value = Ddtos.SelectedValue;
cmd.Parameters.AddWithValue("#driver", SqlDbType.NVarChar).Value = Tbdri.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
When I run the program it fails, when I execute without the #rate parameter, everything works fine, but I want to execute with the #rate parameter.
I am sure the stored procedure is working correctly.

Include #rate as an output parameter in the procedure and the code should be fine

Related

Stored Procedure Not Returning Result from C# Code, but It Returns Value when Executed as Query

I have written stored procedure to get customer id with given inputs.
When executed manually it returns value but not returning any value from
C# code.
create procedure getCustomerID
#firstname CHAR(25),
#lastname CHAR(25),
#middlename as CHAR(25)=null,
#DOB datetime,
#CustomerState as CHAR(25)=null,
#CustomerNumber INTEGER,
#ID nvarchar(25) output
as
begin
....
...
set #ID='something'
end
USE [TestDB]
GO
declare #ID nvarchar(25)
EXECute [dbo].[getCustomerID]
'A', 'B','C','1963-09-06','', 12345, #ID out
print 'ID:'+#ID
GO
OUTPUT
ID: CN0075
C# code:
try
{
using (SqlConnection conn = new SqlConnection("Connectionstring"))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
using (var command = new SqlCommand("getCustomerID", conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#firstname", SqlDbType.Char, 25).Value = "A";
command.Parameters.Add("#lastname", SqlDbType.Char, 25).Value = "B";
command.Parameters.Add("#middlename", SqlDbType.Char, 25).Value = "C";
command.Parameters.Add("#CustomerState", SqlDbType.Char, 25).Value = "";
command.Parameters.Add("#DOB", SqlDbType.DateTime).Value = "1963-09-06";
command.Parameters.Add("#CustomerNumber", SqlDbType.Int).Value = "12345";
command.Parameters.Add("#ID", SqlDbType.NVarChar, 25).Direction =
ParameterDirection.Output;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string retunID = command.Parameters["#ID"].Value.ToString();
}
}
}
}
}
catch (Exception e)
{
Logger.Error(e.Message);
}
It does not throw exception. It executes the the stored procedure and does
not go inside While(reader.read()) loop and read data.
in your sp use select instate of print
create procedure getCustomerID
#firstname CHAR(25),
#lastname CHAR(25),
#middlename as CHAR(25)=null,
#DOB datetime,
#CustomerState as CHAR(25)=null,
#CustomerNumber INTEGER,
#ID nvarchar(25) output
as
begin
....
...
set #ID='something'
select #ID
end
USE [TestDB]
GO
declare #ID nvarchar(25)
EXECute [dbo].[getCustomerID]
'A', 'B','C','1963-09-06','', 12345, #ID out
select 'ID:'+#ID
GO
enter image description here

How to return Identity Column from SQL Server procedure in C# code

I am looking to Insert a row into a table and return the Identity column in c# code. I cannot seem to get the syntax quite right.
Here is the storted procedure
ALTER PROCEDURE [dbo].[sp_InsertIssue]
#Application nchar(20) = NULL ,
#Version nchar(10) = NULL ,
#CreatedBy NVARCHAR(30) = NULL ,
#AssignedTo nVARCHAR(max) = NULL ,
#Description nVARCHAR(max) = NULL ,
#UserId INT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Issue
(
Application ,
Version ,
CreatedBy ,
AssignedTo ,
Description ,
UserId
)
VALUES
(
#Application ,
#Version ,
#CreatedBy ,
#AssignedTo ,
#Description ,
#UserId
)
RETURN SCOPE_IDENTITY()
END
Here is the C# Code
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "sp_InsertIssue ";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = m_Connection;
SqlParameter parm = new SqlParameter("#IssueId", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add("#Application", SqlDbType.VarChar).Value = p_Application;
cmd.Parameters.Add("#Version", SqlDbType.VarChar).Value = p_Version;
cmd.Parameters.Add("#CreatedBy", SqlDbType.VarChar).Value = p_CreatedBy;
cmd.Parameters.Add("#AssignedTo", SqlDbType.VarChar).Value = p_AssignedTo;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = p_Description;
cmd.Parameters.Add("#UserId", SqlDbType.Int).Value = p_UserId;
var returnParameter = cmd.Parameters.Add("IssueId", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
/// send data to db
Int32 id = (int)cmd.ExecuteNonQuery();
Return -1 not the identity column
You have to make some changes :
SELECT SCOPE_IDENTITY() is beter than Return SCOPE_IDENTITY()
in your code you have to change also cmd.ExecuteNonQuery()
with int id = Convert.ToInt32(cmd.ExecuteScalar());
Changing my answer completely after reading your code more closely :) You were so close
Change:
Int32 id = (int)cmd.ExecuteNonQuery();
To:
cmd.ExecuteNonQuery(); // this returns the # of "rows affected"
Int32 id = (int)returnParameter.Value

C# SQL output code issue

I am having an issue with the code below, I keep getting
"Procedure or function 'InsertFile' Expects parameter '#ID', which was
not supplied"
I must be doing something wrong in the returning of the ID.
ALTER PROCEDURE [dbo].[InsertFile]
-- Add the parameters for the stored procedure here
--#AssetID INT,
#ComputerName varchar(max),
#FilePath varchar(max),
#Owner varchar(100),
#Size int,
#Extension varchar(50),
#CreationDate datetime,
#ModifiedDate datetime,
#AccessedDate datetime,
#ID int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS (SELECT * From DC_Files Where computerName = #ComputerName AND FilePath = #FilePath)
BEGIN
INSERT INTO DC_Files (ComputerName, FilePath, Owner, Size, Extension, CreationDate, ModifiedDate, AccessedDate)
VALUES (#ComputerName, #FilePath, #Owner, #Size, #Extension, #CreationDate, #ModifiedDate, #AccessedDate)
END
ELSE
BEGIN
UPDATE DC_Files
SET Owner = #Owner, Size = #Size, CreationDate = #CreationDate, ModifiedDate = #ModifiedDate, AccessedDate = #AccessedDate
WHERE computerName = #ComputerName AND FilePath = #FilePath
END
SET #ID = SCOPE_IDENTITY()
END
The C# code:
SqlCommand cmd = new SqlCommand("InsertFile",conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#AssetID", FileInfo);
cmd.Parameters.AddWithValue("#ComputerName", Environment.MachineName);
cmd.Parameters.AddWithValue("#FilePath", FilePath);
cmd.Parameters.AddWithValue("#Owner", FileSecurity.GetOwner(typeof(NTAccount)).Value);
cmd.Parameters.AddWithValue("#Size", FileInfo.Length);
cmd.Parameters.AddWithValue("#Extension", FileInfo.Extension);
cmd.Parameters.AddWithValue("#CreationDate", FileCreationTime);
cmd.Parameters.AddWithValue("#ModifiedDate", FileModifiedTime);
cmd.Parameters.AddWithValue("#AccessedDate", FileAccessedTime);
var returnParameter = cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.ExecuteNonQuery();
You have to set the Direction to Output since by default the Direction of all Parameter is Input.
// Create parameter with Direction as Output
SqlParameter returnParameter = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(returnParameter);
Try Adding output parameter as follows in ur C# code
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#ID";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);

Procedure or function expects parameter , which was not supplied

Procedure or function 'login' expects parameter '#Abc', which was not supplied
4 hours searching and trying and no use I already supplied this parameter (copy/paste) and the number of parameters given to procedure is the same of procedure and in order.
#Abc is an output parameter.
Stored procedure definition:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[login]
(
#Abc int output,
#firstname varchar(255) output,
#lastname varchar(255) output,
#Email varchar(255),
#pass varchar(255)
)
As
begin
if not exists (select Email from user_1 where email=#email)
select #Abc = 0
else begin
if not exists (
select Email from user_1 where email =#Email and password = #pass
)
select #Abc = 1
else
select #Abc = 2,#firstname = u.first_name ,#lastname=u.last_name from user_1 u where u.email = #email
end
end
Code to call the stored procedure:
myCon.Open();
TextBox username = UserName;
TextBox password = Password;
SqlCommand myCommand = new SqlCommand("login", myCon);
SqlParameter count= myCommand.Parameters.Add("#Abc", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter fnp = myCommand.Parameters.Add("#firstname", SqlDbType.VarChar,255);
fnp.Direction = ParameterDirection.Output;
SqlParameter lnp = myCommand.Parameters.Add("#lastname", SqlDbType.VarChar, 255);
lnp.Direction = ParameterDirection.Output;
myCommand.Parameters.AddWithValue("#Email",username.Text);
myCommand.Parameters.AddWithValue("#pass", password.Text);
myCommand.ExecuteNonQuery();
myCon.Close();
You have omitted:
myCommand.CommandType = CommandType.StoredProcedure;
So the command sent to the DB is a malfed sp_executeSQL call instead of the desired exec login
FYI there is also a shorter syntax:
myCommand.Parameters.Add("#Abc", SqlDbType.Int).Direction = ParameterDirection.Output;

Stored procedure error when use computed column for ID

I got the error:
Procedure or function usp_User_Info3 has too many arguments specified
When I run the program. I don't know the error in SP or in C# code. I have to display the Vendor_ID after the user clicks the submit button. Where the thing going wrong here ?
Table structure :
CREATE TABLE User_Info3
(
SNo int Identity (2000,1) ,
Vendor_ID AS 'VEN' + CAST(SNo as varchar(16)) PERSISTED PRIMARY KEY,
UserName VARCHAR(16) NOT NULL,
User_Password VARCHAR(12) NOT NULL,
User_ConPassword VARCHAR(12) NOT NULL,
User_FirstName VARCHAR(25) NOT NULL,
User_LastName VARCHAR(25) SPARSE NULL,
User_Title VARCHAR(35) NOT NULL,
User_EMail VARCHAR(35) NOT NULL,
User_PhoneNo VARCHAR(14) NOT NULL,
User_MobileNo VARCHAR(14)NOT NULL,
User_FaxNo VARCHAR(14)NOT NULL,
UserReg_Date DATE DEFAULT GETDATE()
)
Stored Procedure :
ALTER PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#Vendor_ID VARCHAR(10) OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_OtherEmail VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,
User_LastName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,
#User_Title,#User_OtherEmail,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
SELECT Vendor_ID From User_Info3 WHERE SNo = #SNo
END
C# Code :
protected void BtnUserNext_Click(object sender, EventArgs e)
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info3";
System.Data.SqlClient.SqlParameter SNo=cmd.Parameters.Add("#SNo",System.Data.SqlDbType.Int);
System.Data.SqlClient.SqlParameter Vendor_ID=cmd.Parameters.Add("#Vendor_ID",
System.Data.SqlDbType.VarChar,10);
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text;
cmd.Parameters.Add("#User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text;
cmd.Parameters.Add("#User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text;
cmd.Parameters.Add("#User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text;
cmd.Parameters.Add("#User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text;
cmd.Parameters.Add("#User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text;
cmd.Parameters.Add("#User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text;
cmd.Parameters.Add("#User_PhoneNo", SqlDbType.VarChar).Value =txtRegTelephone.Text;
cmd.Parameters.Add("#User_MobileNo", SqlDbType.VarChar).Value =txtRegMobile.Text;
cmd.Parameters.Add("#User_FaxNo", SqlDbType.VarChar).Value =txtRegFax.Text;
cmd.Connection = SqlCon;
try
{
Vendor_ID.Direction = System.Data.ParameterDirection.Output;
SqlCon.Open();
cmd.ExecuteNonQuery();
string VendorID = cmd.ExecuteScalar() as string;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + ");
SqlCon.Close();
}
}
You're not setting the direction of the #SNo parameter
You're calling the command twice - Just call it with ExecuteScalar if you want the return value.
You're not setting the value of your #Vendor_ID output parameter in the stored procedure.
If I had to guess, I would wager that cmd is being re-used and has parameters from a previous call left in it. One option would be to call cmd.Parameters.Clear(), but frankly I see little point re-using this SqlCommand instance - it would be better to use a new command each time:
using(var cmd = SqlCon.CreateCommand()) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_User_Info3";
// TODO: add parameters
// TODO: call one of the Execute* methods
}
User_OtherEmail column doesnt exist in the table
Correct Stored Procedure
Create PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#Vendor_ID VARCHAR(10) OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_Email VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,
User_LastName,User_Title,User_Email,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,
#User_Title,#User_Email,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
SELECT Vendor_ID From User_Info3 WHERE SNo = #SNo
END
and the c# code to be modified accordingly .
After all these answers from great minds I can't believe you are still stuck. Here are my suggestions
In your PROC
'maintain this in your parameter
#Vendor_ID VARCHAR(10) OUTPUT,
Update to Select VendorID into #VendorID. See the second line
SET #SNo = Scope_Identity()
SELECT #Vendor_ID=VendorID From User_Info3 WHERE SNo = #SNo
In C#, do not call ExecuteScalar use ExecuteNonQuery
string newVendorID = "";
try
{
Vendor_ID.Direction = System.Data.ParameterDirection.Output;
SqlCon.Open();
cmd.ExecuteNonQuery();
if(Vendor_ID.Value != null)
newVendorID = Vendor_ID.Value.ToString();
}
You could rename the Vendor_ID parameter to something more meaningful, like VendorIDParam. Hope this helps?
Thanks for all your response.After i modify many times the C# code and SP according to your ideas, finally i got the answer for my question. I removed 'Vendor_ID' from my SP and add few codes in my code as shown below.
Stored procedure :
ALTER PROCEDURE [dbo].[usp_User_Info3]
#SNo INT OUTPUT,
#UserName VARCHAR(30),
#User_Password VARCHAR(12),
#User_ConPassword VARCHAR(12),
#User_FirstName VARCHAR(25),
#User_LastName VARCHAR(25),
#User_Title VARCHAR(35),
#User_OtherEmail VARCHAR(30),
#User_PhoneNo VARCHAR(14),
#User_MobileNo VARCHAR(14),
#User_FaxNo VARCHAR(14)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO User_Info3 (UserName,User_Password,User_ConPassword,User_FirstName,User_Title,User_OtherEmail,User_PhoneNo,User_MobileNo,User_FaxNo)
VALUES (#UserName,#User_Password,#User_ConPassword,#User_FirstName,#User_LastName,#User_Title,#User_OtherEmail,#User_PhoneNo,#User_MobileNo,#User_FaxNo)
SET #SNo = Scope_Identity()
END
C# Code :
protected void BtnUserNext_Click(object sender, EventArgs e)
{
SqlCon.Open();
SqlCommand cmd2 = new SqlCommand("usp_User_Info3", SqlCon);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "usp_User_Info3";
System.Data.SqlClient.SqlParameter SNo=cmd2.Parameters.Add("#SNo", System.Data.SqlDbType.Int);
cmd2.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUserName.Text.Trim();
cmd2.Parameters.Add("#User_Password", SqlDbType.VarChar).Value = txtRegPassword.Text.Trim();
cmd2.Parameters.Add("#User_ConPassword", SqlDbType.VarChar).Value = txtRegConPassword.Text;
cmd2.Parameters.Add("#User_FirstName", SqlDbType.VarChar).Value = txtRegFName.Text.Trim();
cmd2.Parameters.Add("#User_LastName", SqlDbType.VarChar).Value = txtRegLName.Text.Trim();
cmd2.Parameters.Add("#User_Title", SqlDbType.VarChar).Value = txtRegTitle.Text.Trim();
cmd2.Parameters.Add("#User_OtherEmail", SqlDbType.VarChar).Value = txtOtherEmail.Text.Trim();
cmd2.Parameters.Add("#User_PhoneNo", SqlDbType.VarChar).Value = txtRegCode1.Text;
cmd2.Parameters.Add("#User_MobileNo", SqlDbType.VarChar).Value = txtRegCode2.Text;
cmd2.Parameters.Add("#User_FaxNo", SqlDbType.VarChar).Value = txtRegCode3.Text;
cmd2.Connection = SqlCon;
try
{
SNo.Direction = System.Data.ParameterDirection.Output;
cmd2.ExecuteScalar();
string VendorID = "VEN" + cmd2.Parameters["#SNo"].Value.ToString();
}
finally
{
string url = "../CompanyBasicInfo.aspx?Parameter=" + Server.UrlEncode(" + VendorID + ");
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Login created successfully');window.location.href = '" + url + "';", true);
SqlCon.Close();
}
}

Categories

Resources