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

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) = '',

Related

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.

Very Strange SqlClient error with SmallDatetime parameter in SQL Server 2014 stored proc

I've been stumped with the following error for the past hour:
"Procedure or function 'write_call' expects parameter '#Date', which was not supplied."
The #date parameter is a smalldatetime. I am trying to pass the value #1/27/2009 04:32:00 PM#
I am using SQLExpress 2014.
The same stored proc has been in production on SQLExpress 2008
T-SQL Stored Proc:
ALTER proc [dbo].[write_call]
(
#Date smalldatetime, #Duration smallint, #Ring tinyint, #Extension smallint = null, #Number varchar(20) = null, #LineID smallint,
#AccountID smallint = null, #AccountName varchar(30) = null, #UnitID smallint = null, #UnitName varchar(30) = null, #AreaName varchar(100) = null, #CallType char(1) = null,
#CallCode varchar(6) = null, #Rate numeric(5,2) = 0.0, #Cost numeric(12,2) = 0.0, #TAC varchar(10) = null
)
as
declare #id int=0, #old_acctid int=0 --, #old_rate numeric(5,2)=0.0, #old_cost numeric(12,2)=0.0
select #id=o.ID,#old_acctid=o.AccountID from OutboundCalls o where o.Date=#Date and o.Duration=#Duration and o.Number=#Number
if #id=0
begin
insert into _OutboundCalls (Date, Duration, Ring, Extension, Number, LineID, AccountID, AccountName, UnitID, UnitName, AreaName, CallType,CallCode, Rate, Cost, TAC,redirected,contactid,CompanyID,CompanyName)
values (#Date, #Duration, #Ring, #Extension, #Number, #LineID, #AccountID, #AccountName, #UnitID, #UnitName, #AreaName, #CallType, #CallCode, #Rate, #Cost, #TAC,1,0,1,'PricewaterhouseCoopers')
end
else if #id>0 and #old_acctid<>#AccountID
update OutboundCalls set AccountID=#AccountID, UnitID=#UnitID,AccountName=#AccountName,UnitName=#UnitName
where OutboundCalls.ID=#id
VB.NET 2015:
Private Sub write_call(c As CallInfo)
Using cnn = New SqlClient.SqlConnection(connString)
Using cmd = New SqlClient.SqlCommand("write_call", cnn)
cmd.Parameters.AddWithValue("#Date", c.dt)
cmd.Parameters.AddWithValue("#Duration", c.secDurn)
cmd.Parameters.AddWithValue("#Ring", 0)
cmd.Parameters.AddWithValue("#Extension", c.src)
cmd.Parameters.AddWithValue("#Number", c.dst)
cmd.Parameters.AddWithValue("#LineID", c.lineId)
cmd.Parameters.AddWithValue("#AccountID", c.account_id)
cmd.Parameters.AddWithValue("#AccountName", c.account_name)
cmd.Parameters.AddWithValue("#UnitID", c.unit_id)
cmd.Parameters.AddWithValue("#UnitName", c.unit_name)
cmd.Parameters.AddWithValue("#AreaName", c.area?.Name)
cmd.Parameters.AddWithValue("#CallType", c.dst_type)
cmd.Parameters.AddWithValue("#CallCode", c.callcode)
cmd.Parameters.AddWithValue("#Rate", c.rate?.rate)
cmd.Parameters.AddWithValue("#Cost", c.Cost)
cmd.Parameters.AddWithValue("#TAC", c._oC)
cnn.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Stop
End Try
End Using
End Using
End Sub
It seems that your code misses to set the CommandType property. This property defaults to CommandType.Text and it is appropriate when you pass a sql string as the CommandText.
If you pass the name of a stored procedure you need to set
cmd.CommandType = CommandType.StoredProcedure
without this setting the behavior of the SqlCommand is unpredictable.

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

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.

SQL server Nvarchar parameters

I Have created an SP to search against many tables in the db based on string sent form ado
the Vb code
Shared ReadOnly Property Connection() As String
Get
Return ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
End Get
End Property
Function GetData(ByVal SearchKey As String) As DataTable
Dim sqlConn As New SqlConnection(Connection)
Dim ds As New DataSet
Dim sqlCmd As New SqlCommand("Search_List")
Dim sqlAdapter As New SqlDataAdapter
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = sqlConn
sqlAdapter.SelectCommand = sqlCmd
sqlCmd.Parameters.Add(New SqlParameter("#SearchKey", SqlDbType.NVarChar, 255, ParameterDirection.Input, True, CByte(0), CByte(0), "SearchKey", DataRowVersion.Default, SearchKey))
sqlCmd.Parameters.Add("RerurnValue", SqlDbType.Int)
sqlCmd.Parameters("RerurnValue").Direction = ParameterDirection.ReturnValue
Try
sqlConn.Open()
sqlAdapter.Fill(ds, "Result")
sqlConn.Close()
Catch ex As Exception
Exit Function
End Try
Return ds.Tables("Result")
End Function
and the SQL SP is :
ALTER PROCEDURE [dbo].[Search_List](
#SearchKey NVARCHAR(200)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Rc bigint
DECLARE #Err bigint
set #SearchKey = '%'+#SearchKey+'%'
CREATE
TABLE
#Temp
(
ID BIGINT,
elementType NVARCHAR(10),
NameAr NVARCHAR(255),
NAmeEn NVARCHAR(255),
DescAr NVARCHAR(MAX),
DescEn NVARCHAR(MAX),
URL NVARCHAR(MAX)
)
INSERT INTO #Temp
SELECT
Id
,'C'
,NameAr
,NameEn
,DescAr
,DescEn
,'Counsel.aspx'
FROM
CMS_Councils
Where
(NameAr like #SearchKey
OR
NameEn Like #SearchKey
OR
DescAr Like #SearchKey
OR
DescEn Like #SearchKey)
AND
isnull(Status,0) = 1
select * from #Temp
end
As you can see I have declared argument in VB as Nvarchr and SQL parameter #SearchKey as Nvarchar also if I send english data in #SearchKey search returns correct data, but if I tried to send arabic string in #SearchKey no results appeared knowing that there is arabic data inside the table
Am I missing something?
What Should I do further than that to allow arabic search?
You can try specifying a collation using the COLLATE keyword:
You'd need to specify arabic afterwards, for instance: COLLATE arabic_ci_as
SELECT
Id
,'C'
,NameAr
,NameEn
,DescAr
,DescEn
,'Counsel.aspx'
FROM
CMS_Councils
Where
(NameAr like #SearchKey
OR
NameEn Like #SearchKey
OR
DescAr Like #SearchKey
OR
DescEn Like #SearchKey)
AND
isnull(Status,0) = 1
COLLATE arabic_ci_as

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.