Additional information: Procedure or function 'spCustomerRegistration' expects parameter '#other', which was not supplied - sql

I am trying to insert data into an MS SQL database table and gets this error when the other field is empty
The Other Column has Allow Nulls set to true
Additional information: Procedure or function 'spCustomerRegistration' expects parameter '#other', which was not supplied.
Model Code
SqlCommand cmd = new SqlCommand("spCustomerRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#firstname", txtFirstName);
cmd.Parameters.AddWithValue("#lastname", txtLastName);
cmd.Parameters.AddWithValue("#stateid", ddLocation1);
cmd.Parameters.AddWithValue("#urbanrural", txtStatUR);
cmd.Parameters.AddWithValue("#cityid", city_id);
cmd.Parameters.AddWithValue("#areaid", area_id);
cmd.Parameters.AddWithValue("#streetid", street_id);
cmd.Parameters.AddWithValue("#townid", town_id);
cmd.Parameters.AddWithValue("#villageid", village_id);
cmd.Parameters.AddWithValue("#houseno", txtHouseNo);
cmd.Parameters.AddWithValue("#dob", Convert.ToDateTime(DOB));
cmd.Parameters.AddWithValue("#customeremail", txtEmail);
cmd.Parameters.AddWithValue("#customerphone", _phone_number);
cmd.Parameters.AddWithValue("#gender", ddGender);
cmd.Parameters.AddWithValue("#password", dal.Encryptdata(txtPassword));
cmd.Parameters.AddWithValue("#customeripaddress", _cip);
cmd.Parameters.AddWithValue("#regcode", _regcode);
cmd.Parameters.AddWithValue("#customerguid", _CustomerGuid);
cmd.Parameters.AddWithValue("#other", txtOthers);
cmd.Parameters.Add("#retval", SqlDbType.Int);
cmd.Parameters["#retval"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#userid", SqlDbType.Int, 0, "id");
cmd.Parameters["#userid"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
retval = (int)cmd.Parameters["#retval"].Value;
pk_uid = (int)cmd.Parameters["#userid"].Value;
con.Close();
Stored Procedure
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT * FROM CustomerRegistration WHERE CustomerEmail =#customeremail or CustomerPhone=#customerphone )
BEGIN
INSERT INTO CustomerRegistration (FirstName ,LastName ,StateID, Urban_Rural, CityID, AreaID, StreetID, TownID, VillageID, HouseNo, DOB, CustomerEmail, CustomerPhone, Gender, Password, CustomerIPAddress, RegCode, CustomerGuid, Other ) VALUES (#firstname, #lastname, #stateid, #urbanrural, #cityid, #areaid, #streetid, #townid, #villageid, #houseno, #dob, #customeremail, #customerphone, #gender, #password, #customeripaddress, #regcode, #customerguid, #other )
SELECT #userid = SCOPE_IDENTITY();
SET #retval=1
END
ELSE
BEGIN
SET #retval =0
SET #userid =0
END

Sql server does not support null. when any object or value is null then you have to assign value DBNull.Value instead of null.

Related

Get result from Stored Procedure then pass to WPF TextBox

I have this stored procedure that executes fine:
ALTER PROCEDURE [dbo].[SP_GENERATETICKET]
#RESULT AS VARCHAR(255) OUTPUT
AS
BEGIN
DECLARE #D AS DATETIME = GETDATE()
DECLARE #LASTTICKET AS VARCHAR(50) ;
DECLARE #NUM AS VARCHAR(50);
SET #LASTTICKET=(SELECT TOP 1 TICKETNO FROM tblTicket WHERE
MONTH(ENTRYVEHICLE ) = MONTH(#D ) ORDER BY TICKETNO DESC);
IF (CONVERT(VARCHAR(10),YEAR(#D),110) <> CONVERT(VARCHAR(10),YEAR(GETDATE()),110))--IF YEAR IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM = '1'
END
ELSE
BEGIN
IF ISNULL(#LASTTICKET,'1') = '1'--IF MONTH IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM ='1'
END
ELSE
BEGIN
SET #NUM = CAST(CAST (RIGHT(#LASTTICKET,5) AS INT) + 1 AS VARCHAR)
END
END
SET #RESULT = RIGHT(CONVERT(VARCHAR(10),#D,101),2) + '-' + LEFT(CONVERT(VARCHAR(10),#D,101),2) + '-' + RIGHT('0000'+CAST(#NUM AS VARCHAR),5)
SELECT #RESULT
END
I have this Code but it returns null
SqlConnection con = new SqlConnection(gsql.connectionString);
SqlCommand command = new SqlCommand("SP_GENERATETICKET", con);
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Direction = ParameterDirection.Output;
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
What should I do?
there problem is there , you forgot to execute command
command.ExecuteNonQuery()
without executing command you want get result back.
also you forgot to add size for you varchar paramter , so add thing line
result.Size = 8000;
udpated in below code
you code will be , you need to use using to dispose things for you
using(SqlConnection con = new SqlConnection(gsql.connectionString))
{
using(SqlCommand command = new SqlCommand("SP_GENERATETICKET", con))
{
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Size = 8000;//add parameter size
result.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();//this line need to be added
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Parameters are a good practice but for output you cannot have SQL injection (that I know of).
con.Open();
command.CommandType = CommandType.StoredProcedure;
txtTicket.Text = (string)command.ExecuteScalar();
For size you can use this syntax:
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar, 800);

I've tried different ways but still it's throwing an error that cannot convert varchar to int

private void button_submit_Click(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=SQLNCLI11;Data Source=.;Integrated Security=SSPI;Initial Catalog=AdventureWorks2012");
cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_empinfo";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#bid",textBox_BID.Text);
cmd.Parameters.AddWithValue("#job",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#gender",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#maritalstatus",SqlDbType.VarChar).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
label_Job.Text =label_Job.Text + "" + cmd.Parameters["#job"].Value.ToString();
label_gender.Text=label_gender.Text + "" + cmd.Parameters["#gender"].Value.ToString();
label_MStatus.Text=label_MStatus.Text + "" + cmd.Parameters["#maritalstatus"].Value.ToString();
}
My stored procedure with input and output parameters:
alter PROC USP_EMPINFO
#bid AS varchar(20),
#job as varchar(20) output,
#gender as varchar(20) output,
#maritalstatus as varchar(20) output
as
begin
select #Job=JobTitle,#Gender=Gender,#maritalstatus=MaritalStatus from humanresources.employee
where BusinessEntityID = #bid
end
I can only assume that BusinessEntityID is an int (maybe even an identifier). In that case, I would define the sproc parameter #bid as that same field type (int, if that's what it is). The sproc definition, then, wouldn't allow a non-int value to be passed in.
Then, change the c# code to
cmd.Parameters.Add("#bid",SqlDbType.Int).Value=int.Parse(textBox_BID.Text.Trim()); //trim because you're passing in a string that might be padded
If it blows up at that line, you'll know that even c# can't convert the value to an int, so you'll need to do extra field validation work.

Procedure or function 'userpro' expects parameter '#Username', which was not supplied

i am getting error of ExcecuteNonQuery ,i am not getting where i am wrong please help!
SqlConnection con = new SqlConnection(
"Data Source="";Initial Catalog=bunny;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("userpro", con);
CommandType cd = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", TextBox1.Text);
cmd.Parameters.AddWithValue("#Addresss", TextBox2.Text);
cmd.Parameters.AddWithValue("#Contact ", TextBox3.Text);
cmd.Parameters.AddWithValue("#EmailId", TextBox4.Text);
cmd.Parameters.AddWithValue("#Passwords", TextBox5.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", TextBox6.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this is my store procedure
create procedure userpro
#Username varchar (20),
#Addresss varchar (20),
#Contact varchar (20),
#EmailId varchar (20),
#Passwords varchar (20),
#ConfirmPassword varchar (20)
as
begin
if exists (select * from userlogs where Username=#Username)
begin
update userlogs set Addresss=#Addresss,Contact=#Contact,EmailId=#EmailId,Passwords=#Passwords,ConfirmPassword=#ConfirmPassword where Username=#Username
end
else
begin
insert into userlogs(Username,Addresss,Contact,EmailId,Passwords,ConfirmPassword) values (#Username,#Addresss,#Contact,#EmailId,#Passwords,#ConfirmPassword)
end
end
You need to check if TextBox1.Text is not null. If it is procedure will fail because #Username is mandatory. You can resolve this like that:
if(TextBox1.Text == null)
cmd.Parameters.AddWithValue("#Username", DBNull.Value);
else
cmd.Parameters.AddWithValue("#Username", TextBox1.Text);
Or you can make this parameter optional in your userpro procedure:
create procedure userpro
#Username varchar (20) = '',

how to get the auto generated values from sql using c#?

I have an Stored Procedure like below..
CREATE PROCEDURE [dbo].[spMYSPDetails]
#Id VarChar(6),
#Name VarChar(50),
#Limit Money,
#Status VarChar(1),
#Accounts As SmallInt
AS BEGIN
IF(LEN(ISNULL(#strDebtorId, '')) = 0) BEGIN
WHILE 0 = 0 BEGIN
SET #Id = '9' + dbo.fnGenerateRandomCode(5, '0123456789')
IF NOT EXISTS (SELECT 1 FROM mytbl WITH (NOLOCK) WHERE s_Id = #Id) BEGIN
INSERT INTO Mytbl
(D_Id,
D_Name,
D_Limit,
D_Status,
D_Accounts,
D_dtmStamp,
D_Balance)
VALUES
(#Id,
#Name,
#Limit,
#Status,
#Accounts,
GETDATE(),
#Limit)
BREAK
END
I have c# sharp code to call this SP like this...
try
{
string Id = "";
if (hdDId.Value.ToString() != "")
{
Id = hdDId.Value.ToString();
}
objDB.blnParamClear();
objDB.blnParamAdd(ParameterDirection.Input, "#Id", SqlDbType.VarChar, 6, Id.ToString());
objDB.blnParamAdd(ParameterDirection.Input, "#Name", SqlDbType.VarChar, 50, txtName.Value.ToString());
objDB.blnParamAdd(ParameterDirection.Input, "#Limit", SqlDbType.Money, 8, decimal.Parse(txtLimit.Value.ToString()));
objDB.blnParamAdd(ParameterDirection.Input, "#Status", SqlDbType.VarChar, 1, cboStatus.Value);
objDB.blnParamAdd(ParameterDirection.Input, "#intMaxAccounts", SqlDbType.SmallInt, 4, txtAccnts.Value.ToString());
blnResult = (objDB.lngExecuteSP("spMYSPDetails") == 0);
}
Now I want to catch that auto generated(random) ID in C# for my reference. I tried but am unable to Catch.. Is there any way to catch the same id that is generated by SP in SQL.Suggest me something...
Use your #ID as output variable.
#Id VarChar(6) output
Then set your C# parameter
SqlParameter paramOutput = new SqlParameter("#Output", SqlDbType.nVarChar);
paramOutput.Direction = ParameterDirection.Output;
Stored procedures can have return values and output parameters in addition to input parameters.
Use an Output Parameter.
Change ParameterDirection.Input to ParameterDirection.Output when defining a param "#Id".
PS. What are you passing right now to the sproc (Id.ToString()) if the id is generated in the DB? Why aren't you just using autoincrement column?

SQL and ADO.net: Too many arguments specified with output param

ALTER PROCEDURE dbo.uspGetOrderTrackingHeaderInfo
#ContractID varchar(9)
, #SalesRepID int
, #StatusID int
, #TypeID int
, #StartDate datetime
, #EndDate datetime
, #Identity int = null output
AS
INSERT INTO [dbo].[tblOrderTracking]
([ContractID]
,[StatusID]
,[TypeID]
,[SalesRepID]
,[StartDate]
,[EndDate])
VALUES
(#ContractID
,#StatusID
,#TypeID
,#SalesRepID
,#StartDate
,#EndDate)
SET #Identity = Scope_Identity()
Using oConn As New SqlConnection(Me.Master.Master.AdminNetConnString)
Try
With cmd
.Connection = oConn
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.uspInsertOrderTrackingInfo"
.Parameters.AddWithValue("#ContractID", Session("#OrderContractID"))
.Parameters.AddWithValue("#SalesRepID", Integer.Parse(Me.ddlSalesRep.SelectedValue.ToString()))
.Parameters.AddWithValue("#StatusID", Integer.Parse(Me.ddlStatus.SelectedValue.ToString()))
.Parameters.AddWithValue("#TypeID", Integer.Parse(Me.ddlOrderType.SelectedValue.ToString()))
.Parameters.AddWithValue("#StartDate", CDate(txtStartDate.Text.Trim))
.Parameters.AddWithValue("#EndDate", CDate(txtEndDate.Text.Trim))
.Parameters.Add("#Identity", SqlDbType.Int, ParameterDirection.Output)
End With
oConn.Open()
cmd.ExecuteNonQuery()
Session("WorkingOrderID") = cmd.Parameters("#Identity").Value
Response.Redirect("OrderOverview.aspx")
Catch ex As Exception
Me.Master.Master.HandleException(ex, True, "An error occured while attempting to save the order setup information")
Finally
If Not cmd Is Nothing Then
cmd.Dispose()
End If
End Try
End Using
You have posted code for the proc "uspGetOrderTrackingHeaderInfo" and you are calling the proc "uspInsertOrderTrackingInfo". Perhaps you have modified the wrong proc and don't have the output on the Insert one.