Error on SQL Server Insert stored procedure - c#

I'm trying to simply insert data into a table in SQL Server from a C# winforms application.
Currently when the executing the query I'm receiving the error:
Incorrect syntax near 'soAddItems'
Here is my insert code of the class handling my database CRUD operations:
Note: As test data:
itemName = "test"
skuNo = "a123"
itemPrice = 2.99
stockItemToAdd = 3
itemPic = "C:\Users\Name\Pictures\pic.png"**
Code:
public virtual void AddItem(string itemName, string skuNo, double itemPrice, int stockAmountToAdd, string itemPic)
{
using (SqlConnection open = new SqlConnection(connectionString))
{
SqlCommand insertCommand = new SqlCommand("soAddItems", open);
open.Open();
insertCommand.Parameters.Add("#itemName", SqlDbType.NChar).Value = itemName;
insertCommand.Parameters.Add("#skuNo", SqlDbType.VarChar).Value = skuNo;
insertCommand.Parameters.Add("#itemPrice", SqlDbType.Decimal).Value = itemPrice;
insertCommand.Parameters.Add("#instockAmount", SqlDbType.BigInt).Value = stockAmountToAdd;
insertCommand.Parameters.Add("#lastSold", SqlDbType.DateTime).Value = DateTime.Today;
insertCommand.Parameters.Add("#itemPic", SqlDbType.NChar).Value = itemPic;
//***** Error on the execute*****
insertCommand.ExecuteNonQuery();
};
}
SQL Server stored procedure:
ALTER PROC [dbo].[soAddItems]
#itemName nchar,
#skuNo varchar,
#itemPrice float,
#instockAmount bigint,
#lastSold dateTime,
#itemPic varchar
AS
BEGIN
INSERT INTO items (itemName, skuNo, itemPrice, instockAmount, lastSold, itemPic)
VALUES (#itemName, #skuNo, #itemPrice, #instockAmount, #itemPic)
END
Can anyone tell me where I'm going wrong?

You need to tell the SqlCommand command type as stored procedure.
Try this:
insertCommand.CommandType = CommandType.StoredProcedure;

It looks like you forget to assign your SqlCommand.CommandType property.
Because it is Text as a default.
insertCommand.CommandType = CommandType.StoredProcedure;

Besides the missing CommandType.StoredProcedure, you have a second major flaw: if you define a parameter like this: #skuNo varchar - then you get a string of 1 character length!
That's usually not what you want - you should ALWAYS specify a length when defining parameters and variables in T-SQL!
Use: #skuNo varchar(50) or whatever length you need

Related

How can I get multiple output parameters from a stored procedure in a web service in C#?

I have a web service in C#, I use it to consults from tables, but I want to create a WebMethod to call a stored procedure and get back multiples output parameters. I can execute it with output parameters, it doesn't work when I try to call it whit outputs parameters.
This is a sample, I want to get back more that 2 parameters.
Stored procedure:
CREATE OR REPLACE PROCEDURE O_CAPEREZ.GIO_SP (
VNOMBRE IN VARCHAR2,
SALUDO OUT VARCHAR2 )
AS
BEGIN
INSERT INTO G_PRUEBA_SP(NOMBRE)
VALUES (vNOMBRE);
SALUDO:= ('Hello: ' || vNOMBRE);
END;
And this is my code in the web service, when I execute it using output variables I get this error
[HYC00] [Oracle][ODBC]Optional feature not implemented
C# code:
[WebMethod]
public string AP_Data(string curp)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(constr))
{
OdbcCommand cmd = new OdbcCommand("{CALL GIO_SP(?,?)}", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#vNOMBRE", (curp));
cmd.Parameters.Add("#vNOMBRE", OdbcType.VarChar, 18);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Parameters["#SALUDO"].Direction = ParameterDirection.ReturnValue;
cmd.Connection.Close();
string ret = Convert.ToString(cmd.Parameters["#SALUDO"].Value);
return ret;
}
}
You have to add the parameter to the list even if you're not going to set a value there:
cmd.Parameters.Add("#SALUDO", OdbcType.VarChar, 18).Direction = ParameterDirection.Output;
I don't know the the Oracle flavor is different, but in SQL I use ParameterDirection.ReturnValue rather than ParameterDirection.Output.
here's how i do it in MS SQL server 2008 But notice the data type and the lenth of the variables your create must be the same in your table
the stored proc create code
USE DATABASE DATABASE_NAME
GO
CREATE PROC SP_METHOD
#ID_CATIGORY INT,
#NAME VARCHAR (50),
#DESCRIPTION VARCHAR (50)
AS
INSERT INTO TABLE_NAME
([ID_CAT]
,[NAME_PRODUCT]
,[DESC_PRODUCT]
)
VALUES
( #ID_CATIGORY
,#NAME
,#DESCRIPTION )
GO
in the c# code
// Create SqlConnection
SqlConnection conn= new SqlConnection(#"Server=server_name;
DataBase=your_data_base_name;Integrated Security=false;User
Id=user_id;Password=password");
// Open the Connection
if (sqlconnection.State != ConnectionState.Open)
{
conn= .Open();
}
// execute stored_procedure method don't change this
public void ExecuteCommand(string stored_procedure, SqlParameter[] param)
{
SqlCommand sqlcomd = new SqlCommand();
sqlcomd.CommandType = CommandType.StoredProcedure;
sqlcomd.CommandText = stored_procedure;
sqlcomd.Connection = sqlconnection;
if (param !=null)
{
sqlcomd.Parameters.AddRange(param);
}
sqlcomd.ExecuteNonQuery();
}
// close connection method
public void close_conn()
{
if (sqlconnection.State == ConnectionState.Open)
{
sqlconnection.Close();
}
}
// execute and retrieving data Method
public void Add_product(int ID_cat ,string Name_Product,string
Des_Product)
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ID_CAT", SqlDbType.Int);
param[0].Value = ID_cat;
param[1] = new SqlParameter("#NAME_PRODUCT", SqlDbType.VarChar, 50);
param[1].Value = Name_Product;
param[2] = new SqlParameter("#DESC_PRODUCT", SqlDbType.VarChar, 50);
param[2].Value = Des_Product;
ExecuteCommand("StoredProcedure_name", param);
close_conn();
}
and finally you can call this function
Add_product(Convert.ToInt32(ComboBox.SelectedValue),txt_name.Text,
txt_desc.Text);
if there is any part you don't understand lemme know
I've seen many ways to accomplish this.
One way is to Pipe Delimit your select statement in your stored procedure and then use "Value1|Value2".Split('|')[0] to get Value1.
You could also return a table instead of using multiple parameters
DataTable table = new DataTable();
DataAdapter adapter = new DataAdapter(cmd);
adapter.fill(table);
return table.Rows[0]["Greeting"] + table.Rows[0]["Name"];
In the second example you can return as many 'Parameters' as you want, but you will have to assign them to their rightful spots later in your code.
I've also seen an XML way to do this same feature but I won't provide the code here since I don't personally think it is a very good way to do it. The way I've seen done was adding a bunch of XML attributes to a parent tag, and then coming back later and finding the value of each tag later in the code.
In MYSQL it would go like this
CREATE PROCEDURE O_CAPEREZ.GIO_SP (
#vNOMBRE VARCHAR(50))
AS
BEGIN
INSERT INTO G_PRUEBA_SP(NOMBRE)
VALUES (#vNOMBRE);
select 'Hola' as Greeting, #vNOMBRE as Name
END
Also note what Marc_s commented
You need to set the .Direction of the parameter BEFORE making the call to .ExecuteNonQuery()

Error converting nvarchar to data type int

I am getting this error when I try to call my stored procedure form code behind in my website. I have been stuck for quite a while now, as I do not know anywhere I am converting or declaring a value as an integer. This is my SQL statement:
create procedure GetRepPhoneID
#Rep nvarchar(100),
#phoneID nvarchar(100) output
as
set #phoneID = (select concat(CustomerRepPh, '~', cast(RepID as nvarchar(100))) as 'PhoneAndID'
from Reps
where CustomerRep=#Rep)
return #phoneID
go
Then from my c# code behind I am trying to call the stored procedure:
public static string GetRepPhone(string Rep)
{
string Connection = WebConfigurationManager.ConnectionStrings["JDC_DatabaseConnectionString"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Connection);
//This funciton will take all of the values and create them.
try
{
sqlConnection.Open();
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetRepPhoneID"; //getting the procedure created in SQL.
SqlParameter CustomerParam = new SqlParameter();
CustomerParam.ParameterName = "Rep";
CustomerParam.SqlDbType = SqlDbType.NVarChar;
CustomerParam.Value = Rep;
CustomerParam.Direction = ParameterDirection.Input;
//We are using an output parameter not a return one because it is a string.
SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100);
ReturnParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(CustomerParam);
cmd.Parameters.Add(ReturnParam);
cmd.ExecuteNonQuery();
sqlConnection.Close();
return ReturnParam.Value.ToString();
}
I am doing the same thing multiple times in my code, but they all return integers so there has been no error thrown so I know it should work. The error is being thrown on the cmd.ExecuteNonQuery() line. The exact error is:
Conversion failed when converting the nvarchar value '(111)222-6666~29' to data type int.
I understand that I cannot convert that string to an integer, but I do not see anywhere in my code I am declaring an integer, or I am trying to convert.
Any help will be appreciated. Thanks.
You are confusing a RETURN value for an OUTPUT parameter. A RETURN is an optional status code of type INT. Declare another parameter as OUTPUT.
Meaning, this is invalid in the Stored Procedure:
return #phoneID
Instead, add #phoneID nvarchar(100) OUTPUT to the parameter list and remove the DECLARE #PhoneID:
CREATE PROCEDURE GetRepPhoneID
(
#Rep NVARCHAR(100),
#phoneID NVARCHAR(100) OUTPUT
)
AS
SET NOCOUNT ON;
SELECT #phoneID = concat(CustomerRepPh, '~', RepID)
FROM Reps
WHERE CustomerRep = #Rep;
The above represents the entire proc. You don't need the RETURN or the SET.
Then in the C# code, you need to change how that parameter is specified:
SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100);
ReturnParam.Direction = ParameterDirection.Output;
Then remove this line as it is not needed since the value of the parameter will remain after the connection is closed:
string PhoneAndID = cmd.Parameters[1].Value.ToString();
And change the return to be:
return ReturnParam.Value.ToString();
Lastly, you probably need to update the declaration of the input param as follows:
SqlParameter CustomerParam = new SqlParameter("Rep", SqlDbType.NVarChar, 100);
CustomerParam.Value = Rep;
CustomerParam.Direction = ParameterDirection.Input;

Insert a file path string into SQL database via C# code

In SQL:
INSERT INTO [dbo].[tblFiles]
([FullFilePath]
,[LastModified])
VALUES
('P:\test\test.csv',
null)
This will store the full path in the database :)
However, I need to do this in code.
SqlConnection connection = new SqlConnection(DatabaseHelper.ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand( "stpInsertFile", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#filepath", System.Data.SqlDbType.VarChar));
command.Parameters["#filepath"].Value = article.FullFilePath;
command.Parameters.Add(new SqlParameter( "#LastModified", System.Data.SqlDbType.DateTime));
command.Parameters["#LastModified"].Value = article.LastModified;
int newArticleID = Convert.ToInt32((decimal)command.ExecuteNonQuery());
command.Dispose();
connection.Close();
connection.Dispose();
return newArticleID;
With this all I get is 'P' in the full path column.
So I tried using LINQ and got the same result.
public int InsertArticleUsingLINQ(tblFile article) {
DataClassesDataContext context = new DataClassesDataContext();
tblFile newFileEntry = new tblFile();
newFileEntry.FullFilePath = article.FullFilePath;
newFileEntry.LastModified = article.LastModified;
context.tblFiles.InsertOnSubmit(newFileEntry);
context.SubmitChanges();
return newFileEntry.ID;
}
I'm not doing anything with the string before passing it to the database insert functions. I read that you need to escape the backslash but it seems to be escaping on the quote. Also read that you need an # symbol before the sql but how do you add this to a parameter?
warning: since you didn't share the stored procedure code this is just a wild guess.
did you set the size of the #filePath parameter in the definition of your stored procedure?
if you declare it as:
create procedure stpInsertFile
#filepath varchar,
#LastModified datetime
as
...
then you parameter is created as varchar(1) because of the default behaviour of varchar datatype and that would produce the result you get.please check reference documentation for char and varchar datatype on ms website.
if stpInsertFile is a Stored Procedure you will have to set in your code:
...
command.CommandType = CommandType.StoredProcedure;
else you have to set the query string in your command:
SqlCommand command = new SqlCommand( "INSERT INTO [dbo].[tblFiles] ([FullFilePath] [LastModified]) VALUES (#filepath,#LastModified)", connection);
...
Of the above options, the ADO code did not copy the full path, even with manually adding quotes. All I ever got was one character in the database.
On further inspection, the parameter was of type Varchar(1) !!! I changed this to Varchar(255) an it worked.
Note, the LINQ to SQL function did insert the full path as this was not using the Stored Procedure.
Apologies for the mistake.

How can I obtain a value from a stored procedure (SELECT COUNT) in c#

I'm using a stored procedure to count and validate if a username already exists in the database, but the problem isn't there, my problem is when I try to obtain the value of the SELECTION in C# in some blogs I found this code:
// Create ConnectionString
string connectionString = ConfigurationManager.ConnectionStrings["ProjectPractice"].ConnectionString;
// Check if the username is not in the DataBase
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmo = new SqlCommand("spBuscaUsuarioMail", con);
cmo.CommandType = CommandType.StoredProcedure;
cmo.Parameters.AddWithValue("#Username", 1);
SqlParameter NroUserName = new SqlParameter("#Num_de_Usuarios", 0);
NroUserName.Direction = ParameterDirection.Output;
cmo.Parameters.Add(NroUserName);
con.Open();
int contarUsername = Int32.Parse(cmo.Parameters["#Num_de_Usuarios"].Value.ToString());
This seems to be great! And it looks like function very well but then in the last part int contarUsername = Int32.Parse... C# gives me an exception that is the next:
NullReferenceException was unhandled by user code.
Object reference not set o an instance of an object.
Then, in troubleshooting tips I read:
Check to determine if the object is null before calling the method.
Use the "new keyword to create an object instance.
Get general help for this exception.
I tried a lot of things, but now I feel really tired and I can't think in a new solution.
This is the stored procedure I'm using:
CREATE PROCEDURE spBuscaUsuarioMail
#Username CHAR (25),
#Num_de_Usuarios INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
SELECT #Num_de_Usuarios = COUNT (UserName)
FROM dbo.Usuarios
WHERE UserName = #Username
END
EXEC spBuscaUsuarioMail '1', #Num_de_Usuarios OUTPUT
SELECT #Num_de_Usuarios
There's something wrong with your parameters....
In the stored procedure, you have
#Username CHAR (25),
#Num_de_Usuarios INT OUTPUT
yet in your C# code, you set up both of them as int, it seems:
cmo.Parameters.AddWithValue("#Username", 1);
SqlParameter NroUserName = new SqlParameter("#Num_de_Usuarios", 0);
NroUserName.Direction = ParameterDirection.Output;
cmo.Parameters.Add(NroUserName);
I think you need to set up the #Username parameter as a string - and give it some meaningful value!
cmo.Parameters.Add("#Username", SqlDbType.Char, 25).Value = "Steve"; // or whatever
And of course, as #Steve already mentioned: you need to actually execute your stored procedure before you can read out the OUTPUT parameter!
If you don't execute the command it is really difficult to get the value of an output parameter
cmo.Parameters.Add(NroUserName);
con.Open();
cmo.ExecuteNonQuery();
int contarUsername = Convert.ToInt32(cmo.Parameters["#Num_de_Usuarios"].Value);
Also the last two lines of the Stored procedure, if they are really in the sp code are meaningless, you don't need them and you get a recursive call on the same stored procedure until somethink breaks . You should remove them
-- remove these two lines
EXEC spBuscaUsuarioMail '1', #Num_de_Usuarios OUTPUT
SELECT #Num_de_Usuarios
Also look at the answer from #marc_s, he points to another problem in your code.
This is the solution. It works!
string connectionString = connectionString = ConfigurationManager.ConnectionStrings["ProjectPractice"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmo = new SqlCommand("spBuscaUsuario", con);
cmo.CommandType = CommandType.StoredProcedure;
cmo.Parameters.Add("#Username", SqlDbType.Char, 25).Value = txtUsername.Text;
SqlParameter NroUserName = new SqlParameter("#Num_de_Usuarios", 0);
NroUserName.Direction = ParameterDirection.Output;
cmo.Parameters.Add(NroUserName);
con.Open();
cmo.ExecuteNonQuery();
int contarUsername = Int32.Parse(cmo.Parameters["#Num_de_Usuarios"].Value.ToString());
And this is the Stored Procedure...
CREATE PROCEDURE spBuscaUsuario
#Username CHAR (25),
#Num_de_Usuarios INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
SELECT #Num_de_Usuarios = COUNT (UserName)
FROM dbo.Usuarios
WHERE UserName = #Username
END
I expect this code be useful for someone else.

Error While Executing my Stored Procedure in Windows Form

I am trying to INSERT my data into two tables Services and Service-line
Explaining my stored procedure:
It checks for existing ID in the Form
If not found it creates a new record in the Services table the info in the Form, then gets the ID using scope_identity and uses the ID for the Service-Line table.
Also the ID is returned to the Form and stays tre.
Later while inserting second record in Service-Line, the stored procedure checks for existing ID; if found, this time, it takes the ID from the Form and uses it in the Service-Line
This Is my stored procedure
please bear with me, as I am working in this code and testing, a lot of line are commented out
ALTER PROCEDURE [dbo].[InsertServiceServiceLine] (
--Services Entry
--FOR IF CONDITION ---CHECK THE DEFAULT VALUE IN THE FORM on SID
#ExistingSID int,
--SEELCT PARAMETES DEF VALUES
#ComboBoxSelectedBike varchar(100),
-- INPUT PARAMETERES FOR NEW RECORD
#CID int,
#Status bit = 1,
#CurrentMeter int,
#Labor decimal(20,0),
#GrandTotal decimal(20,0) = ISNULL,
--#NextService datetime,
--Service Line
#Spare nvarchar(500),
#Quantity int,
#Uprice decimal(20,2),
#Subtotal decimal(20,2)
)
AS
BEGIN
IF (#ExistingSID <= 0)
BEGIN
SET NOCOUNT ON;
DECLARE #BikeID int
SELECT #BikeID = (SELECT BikeID FROM TblBikeNames WHERE BikeName = #ComboBoxSelectedBike)
INSERT INTO [AutoDB_Sample].[dbo].[TblServices]
(CID,BikeID,Status,CurrentMeter,Labor,DateOfService)
VALUES
(#CID,#BikeID,#Status,#CurrentMeter,#Labor,GETDATE())
DECLARE #SID int
SET #SID = SCOPE_IDENTITY()
INSERT INTO [AutoDB_Sample].[dbo].[TblServiceLine]
(SID,Spare,Quantity,Uprice,Subtotal,DateCreated)
VALUES
(#SID,#Spare,#Quantity,#Uprice,#Subtotal,GETDATE())
RETURN #SID
END
ELSE
BEGIN
INSERT INTO [AutoDB_Sample].[dbo].[TblServiceLine]
(SID,Spare,Quantity,Uprice,Subtotal,DateCreated)
VALUES
(#ExistingSID,#Spare,#Quantity,#Uprice,#Subtotal,GETDATE())
END
END
It gives me an error when I use this stored procedure in a C# Windows Forms
Procedure or Function has too many Arguments
Here's a screenshot of the error
I thought that Putting my login in SP would be great and improve the performance of my application. But now am stuck.
This is my C# Code
public void AddItemIntoServices_ServiceLine()
{
ConnectionStringSettings consetting = ConfigurationManager.ConnectionStrings["AutoDB"];
String ConnectionString = consetting.ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open(); // open the connection
// Specify the name of the Stored Procedure you will call
String SP_Name = "InsertServiceServiceLine";
// Create the SQL Command object and specify that this is a SP.
SqlCommand cmd = new SqlCommand(SP_Name, con);
cmd.CommandType = CommandType.StoredProcedure;
// Specify values for the input parameters of our Stored Procedure
// Parameters MUST be named the same as the parameters defined in the Stored Procedure.
//~~ If Condition Parameter ****************************************************************************~~//
int exitstingSID;
if (int.TryParse(LblSID_Data.Text, out exitstingSID)) ;
SqlParameter ExistingSID = new SqlParameter("#ExistingSID", exitstingSID);
ExistingSID.Direction = ParameterDirection.Input;
ExistingSID.DbType = DbType.Int16;
cmd.Parameters.Add(ExistingSID);
//Parameter to select Bike ID from Selected Bike Name
SqlParameter ParamBikeID = new SqlParameter("#ComboBoxSelectedBike", ComboBx_BikeNames.Text);
ParamBikeID.Direction = ParameterDirection.Input;
ParamBikeID.DbType = DbType.String;
cmd.Parameters.Add(ParamBikeID);
//~~ Customer Info ************************************************************************************~~//
//CID Convertion
int P_CID;
if (int.TryParse(LblCID_Data.Text, out P_CID)) ;
cmd.Parameters.AddWithValue("#CID", P_CID);
cmd.Parameters.AddWithValue("#Cname", this.TxtBx_CustomerName.Text);
cmd.Parameters.AddWithValue("#Vnum", this.TxtBx_VehicleNumber.Text);
//~~ Service Info ************************************************************************************~~//
//Labor Convertion
int Laborint;
if (int.TryParse(TxtBxLabor.Text, out Laborint)) ;
SqlParameter ParamLabor = new SqlParameter("#Labor", Laborint);
ParamLabor.Direction = ParameterDirection.Input;
ParamLabor.DbType = DbType.Int16;
cmd.Parameters.Add(ParamLabor);
//CurrentMeterConversion
int currentMeterint;
if (int.TryParse(TxtBx_CurrentMeter.Text, out currentMeterint)) ;
SqlParameter ParamCurrentMeter = new SqlParameter("#CurrentMeter", currentMeterint);
ParamCurrentMeter.Direction = ParameterDirection.Input;
ParamCurrentMeter.DbType = DbType.Int16;
cmd.Parameters.Add(ParamCurrentMeter);
//Return Value
SqlParameter ParamReturn = new SqlParameter("#SID", SqlDbType.Int);
ParamReturn.Direction = ParameterDirection.Output;
ParamReturn.DbType = DbType.Int16;
cmd.Parameters.Add(ParamReturn);
//~~ Service Info ************************************************************************************~~//
//Converstions
Decimal UP, ST;
if (Decimal.TryParse(TxtBx_UnitPrice.Text, out UP)) ;
if (Decimal.TryParse(TxtBxTotal.Text, out ST)) ;
//SpareName
cmd.Parameters.AddWithValue("#Spare", ComboBx_SparesName.Text);
//Quantity
cmd.Parameters.AddWithValue("#Qty", NumericBx_Quantity.Value);
//Unit Price
SqlParameter ParamUp = new SqlParameter("#Uprice", UP);
ParamUp.Direction = ParameterDirection.Input;
ParamUp.DbType = DbType.Decimal;
cmd.Parameters.Add(ParamUp);
//Total
SqlParameter ParamTot = new SqlParameter("Subtotal", ST);
ParamTot.Direction = ParameterDirection.Input;
ParamTot.DbType = DbType.Decimal;
cmd.Parameters.Add(ParamTot);
cmd.ExecuteNonQuery();
String _returnedSID = cmd.Parameters["#SID"].Value.ToString();
LblSID_Data.Text = _returnedSID;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
clear();
ToolStripLable_Status.Text = "New Service Record Created";
}
}
The list of parameters passed through the command collection should match exactly what the stored procedure expects by name, type and direction.
Your list of parameters included in the command collection doesn't match with the parameters required by the stored procedure and thus you get the error.
At first sight I could say:
cmd.Parameters.AddWithValue("#Cname", this.TxtBx_CustomerName.Text);
cmd.Parameters.AddWithValue("#Vnum", this.TxtBx_VehicleNumber.Text);
SqlParameter ParamReturn = new SqlParameter("#SID", SqlDbType.Int);
are parameters added to the command collection but are not present in the stored procedure list of parameters.
On the contrary we have the parameters #status bit and #GrandTotal decimal(20,0) = ISNULL, required by the stored procedure but not present in the list. (By The way, the default syntax for a NULL parameter is #GrandTotal decimal(20,0) = NULL
Finally the stored procedure names a parameter #Quantity but you add a parameter named #Qty.
Now there is also the problem of the parameter types that should match otherwise you risk an automatic conversion at best or a error message stating about type mismatches.
You have numerous parameter of type int but you pass parameters of type Int16 while the correct type is Int32. And there is also a more clear error in the type of the parameter #Labor that is expected to be a decimal by the sp but you add it as an integer (16)
You have 12 parameters in the stored procedure definition (if I counted correctly), however, your code may have more or less than that. There is either one too many parameters defined within the code, or the stored procedure expects a 13th parameter. I think the error mentions the former, but I sometimes get them confused.
Anyway that error is always due to a mismatch in the number of parameters, and make sure the direction (input/output) is setup correctly, and everything is typed OK.

Categories

Resources