Stored procedure or function expects parameter which wasn't supplied - c#

I am trying to execute a stored procedure in a SqlCommand in C#.
This is the code in C#:
string s = ConfigurationManager.ConnectionStrings["connection"].ToString();
SqlConnection conn = new SqlConnection(s);
conn.Open();
SqlCommand cmd = new SqlCommand("Signup1", conn);
cmd.CommandType = CommandType.StoredProcedure;
string password = TextBox2.Text;
cmd.Parameters.Add(new SqlParameter("#email", email));
SqlParameter pass = cmd.Parameters.Add("#password", SqlDbType.VarChar, 50);
pass.Value = password;
SqlParameter usertype = cmd.Parameters.Add("#usrtype", SqlDbType.VarChar, 50);
usertype.Value =usertype.Value;
cmd.ExecuteNonQuery();
conn.Close();
This is the stored procedure:
Create Proc Signup1
#email varchar(20),
#password Varchar(24),
#usrtype Varchar(30)
as
Insert into Members(email, password)
Values(#email, #password)
if #usrtype = 'Normal User'
begin
Insert into Normal_Users(email)
Values(#email)
end
else if #usrtype = 'Development Team'
begin
Insert into Development_Eeams(email)
Values(#email)
end
else if #usrtype = 'Verified Reviewer'
begin
Insert into Verified_reviewers(email)
Values(#email)
end
else
raiserror('Invalid type',16,1)
When I execute the command I get this error
Procedure or function 'Signup1' expects parameter '#password', which was not supplied.
Though I did gave the procedure the value of the parameter, what is the solution? Thanks

string email = //where are you getting the email address
string password = TextBox2.Text;
string s = ConfigurationManager.ConnectionStrings["connection"].ToString();
using (SqlConnection connStr new SqlConnection(s);
using (SqlCommand cmd = new SqlCommand("Signup1", connStr))
{
c.Open();
command.Parameters.Add(new SqlParameter("#email", SqlDbType.VarChar) { Value = email });
command.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar) { Value = password });
command.Parameters.Add(new SqlParameter("#usrtype", SqlDbType.VarChar) { Value = userType }); //Where are you assigning userType
cmd.ExecuteNonQuery();
}
if the top example is to complicated then you can use the Parameters.AddWithValue Function and let the DB Server handle resolving the datatype for example
string email = //where are you getting the email address
string password = TextBox2.Text;
string s = ConfigurationManager.ConnectionStrings["connection"].ToString();
using (SqlConnection connStr new SqlConnection(s);
using (SqlCommand cmd = new SqlCommand("Signup1", connStr))
{
c.Open();
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue"#password", password);
command.Parameters.AddWithValue("#usrtype", userType); //Where are you assigning userType
cmd.ExecuteNonQuery();
}

Related

How to call Stored Procedure from App_Code DataBase Class

I have a method in DataBase class that resides in App_Code which I use to call a Stored Procedure for Login, but when I make the call I get no error but my Login will not complete.
This is the DataBase Class:
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
}
public DataTable CallSP(string UserName, string Password)
{
con = new SqlConnection(#"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
con.Open();
cmd = new SqlCommand("LoginUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = "UserName";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = "Password";
da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
return dt;
}
This is the code I used to call for Login:
DataBaseClass dbClass = new DataBaseClass();
dt = new DataTable();
dt = dbClass.CallSP("UserName", "Password");
if (dt.Rows.Count > 0)
{
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
This is My Stored Procedure:
CREATE PROCEDURE [dbo].[LoginUser] (
#UserName nvarchar(20),
#Password nvarchar(20)
)
AS
SET NOCOUNT ON;
(
SELECT * FROM [User] WHERE Email = #UserName AND Password = #Password
)
Can anyone reproduce my code and tell me why my Login call could not work.
Try do the following changes in the CallSP method:
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = UserName;
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = Password;
Now appling more attention in your code I saw that your parameters are around quotes, so you were passing the literal strings "UserName" and "Password" instead the values.
With this changes you will pass the values from your parameters.
Sorry by my mistakes.
I hope it can help you.

how to fetch data using this coding

using this coding,while i give fruitId ,i need to retrieve fruitname,using this it shows some error..any one help...
string constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("savefruit11", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitsId", int.Parse(TextBox3.Text.Trim()));
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
}
}
Store procedure for the above code.
use[FruitsDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[savefruit11]
#FruitId INT,
#FruitName VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #FruitName = Fruitsname
FROM Fruits1
WHERE FruitsId = #FruitId
END
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
Your parameter is called #Fruitsname, but you get it back with #FruitName. You have an additional s in the first version. Make them consistent by changing the first #FruitsName to #FruitName which will match what you have in the stored procedure.
Or, as Henk suggested in the comments create a const string to contain your parameter name so that it is consistent across all usages.
Use cmd.ExecuteQuery or cmd.ExecuteScalar
//To Execute SELECT Statement
ExecuteQuery()
//To Execute Other Than Select Statement(means to Execute INSERT/UPDATE/DELETE)
ExecuteNonQuery()
with your udpate
s is missing in parameter name in stored procedure
Use the following example way
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.AdventureWorksData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = "HumanResources.uspUpdateEmployeePersonalInfo";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(
new SqlParameter("#EmployeeID", entity.EmployeeID));
command.Parameters.Add(
new SqlParameter("#NationalIDNumber", entity.NationalIDNumber));
command.Parameters.Add(
new SqlParameter("#BirthDate", entity.BirthDate));
command.Parameters.Add(
new SqlParameter("#MaritalStatus", entity.MaritalStatus));
command.Parameters.Add(
new SqlParameter("#Gender", entity.Gender));
connection.Open();
command.ExecuteNonQuery();
}
}
reference from MSDN
http://msdn.microsoft.com/en-us/library/jj635144.aspx

Checking if id and reg already exists

I have this table Profile which has fields with user_Id and regNo and I want to check first if id and email are already exists before proceed to inserting data.
In my code, I am able to validate only one row (either id or reg number), but if I am going to validate the two of them, it gives me an error, saying "Must declare the scalar variable #userid". I don't know if it is with my select that is wrong or something in my code.
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con);
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
//cmdd.Parameters.Add(param1);
SqlDataReader reader = cmdd.ExecuteReader();
if (reader.HasRows)
{
MessageBox("User Id/Registry Number already exists");
}
else
{
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
SqlCommand cmd = new SqlCommand("qry", con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#regno", txtregNo.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
MessageBox("successfully saved!");
}
I am using C# with asp.net.
OK, so this isn't going to work:
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
because you're reassigning the value of the same object. Change that to this:
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
this will add the parameters, two of them, to the SqlCommand object. Now, a little more advice, consider doing this:
using (SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"))
{
con.Open();
using (SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con))
{
...
using (SqlDataReader reader = cmdd.ExecuteReader())
{
...
}
}
}
because right now you're not disposing those object properly.
You see, anything that implements IDisposable should be wrapped in a using statement to ensure the Dispose method is called on it.
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
You are only declaring 1 parameter and overwriting it for both ParameterName and Value.
As an aside, you should consider looking into some type of data access helper or ORM or something to save you the trouble of all that boilerplate SQL connection code.
You are also opening another connection inside of what should already be an open SQL connection.
You are using one instance of sql parameter and passing it two different values thus overriding the first one. Try it like this:
SqlParameter param1 = new SqlParameter("#userid", txtid.Text);
SqlParameter param2 = new SqlParameter("#reg", txtregNo.Text);
Your problem as per the error is that you are reassigning the parameter to #reg after you assign it to #userid.
Try this:
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select user_id from Profile where user_Id = #userid AND RegNo = #reg", con);
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
var id = cmdd.ExecuteReader() as string;
if (String.IsNullOrEmpty(id))
{
//Show error message and exit the method
}
else
{
//Add the row to the database if it didn't exist
}
EDIT:
I added some code to show how you could check if the userId exists in the table. Then you check against the user id itself instead of checking a reader object. Note, i am not at my dev computer right now so I did not compile this, you may have to do some tweaks but the idea is there.

Stored procedure output parameter returns #Value

I'm struggling with this thing for the past hour and I'm sure I'm missing something small, I have a stored procedure in SQL Server 2008 and C# code that I want to return the output parameters of my stored procedure.
SQL :
Alter Procedure dbo.GetAssessment
#UserID int,
#AssessmentName varchar(255),
#Score varchar(100) output,
#Completed varchar(10) output,
#DisplayName nvarchar(128) output,
#Result varchar(2500) output
as
begin
select #Score = A.Score, #Completed = A.Completed, #DisplayName = U.Displayname, #Result = A.Result
from Assessment A
inner join Users U
on U.UserId = A.UserID
where U.UserID = #UserId
and AssessmentName = #AssessmentName
end
GO
C#
String SScore, SName, SResult, SComp;
lblAsse.Text = Request.QueryString["AID"];
InsertAssessment(lblAsse.Text, "No", 2, "N/A", "N/A");
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString))
{
SqlParameter outScore = new SqlParameter("#Score", SqlDbType.VarChar,100){ Direction = ParameterDirection.Output };
SqlParameter outComp = new SqlParameter("#Completed", SqlDbType.VarChar,10){ Direction = ParameterDirection.Output };
SqlParameter outName = new SqlParameter("#DisplayName", SqlDbType.NVarChar, 128) { Direction = ParameterDirection.Output };
SqlParameter outResult = new SqlParameter("#Result", SqlDbType.VarChar,2500){ Direction = ParameterDirection.Output };
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "GetAssessment";
cmd.Parameters.AddWithValue("#AssessmentName", lblAsse.Text);
cmd.Parameters.AddWithValue("#UserId", 2);
cmd.Parameters.Add(outScore);
cmd.Parameters.Add(outComp);
cmd.Parameters.Add(outName);
cmd.Parameters.Add(outResult);
cmd.ExecuteScalar();
SScore = outScore.ToString();
SName = outName.ToString();
SResult = outResult.ToString();
SComp = outComp.ToString();
conn.Close();
lblAsse.Text = SScore;`
Output :
#Score
What can possibly be wrong with me or my code. Please help!
You just need to read out the actual values from your output parameters:
SScore = outScore.Value;
The .ToString() doesn't return the value - it returns the name of the parameter instead...
See the MSDN documentation on SqlParameter for more details.
just need to do this.
Before getting the output parameters you must close the Data reader as
reader.Close();
and then you get output parameters as
SScore = outScore.Value.Tostring();
for more help consult this http://msdn.microsoft.com/en-us/library/ms971497
>Try this its working fine for the multiple output parameter:
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStringEndicia"].ConnectionString)){
using (var sqlCmd = new SqlCommand("endicia.credentialLookup", sqlConnection))
{
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#accountNumber", accountNumber);
SqlParameter outLogin = new SqlParameter("#login", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output };
sqlCmd.Parameters.Add(outLogin);
SqlParameter outPassword = new SqlParameter("#password", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output };
sqlCmd.Parameters.Add(outPassword);
sqlConnection.Open();
sqlCmd.ExecuteNonQuery();
string login, password;
login = outLogin.Value.ToString();
password = outPassword.Value.ToString();
}
}

Prevent users from registering twice

I have a register form and I want to check that the user did not register before.
My code is in below. I think two problems exist: (1) the call method and (2) passing the parameter to the stored procedure. My symptom is that this causes an exception that says the input parameter not initialized.
create procedure fakeuser #username nvarchar(250),#codemeli nchar(10),#email nvarchar(50), #user nvarchar(250) output,#code nchar(10)output,#mail nvarchar(50)output
as
if exists(select username,email,codemeli from karbar where username=#username)
set #user=#username
else if exists(select username,email,codemeli from karbar where codemeli=#codemeli)
set #code=#codemeli
else if exists(select username,email,codemeli from karbar where email=#email)
set #mail= #email
Here is the c# code:
public static string confirm(string username, string email, string codemeli)
{
string constring = "data source=.;database=site;integrated security=true;";
SqlConnection connection = new SqlConnection(constring);
// Command - specify as StoredProcedure
SqlCommand command = new SqlCommand("fakeuser", connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#username", SqlDbType.NVarChar);
param.Direction = ParameterDirection.Input;
param.Value = username;
command.Parameters.Add(param);
SqlParameter param2 = new SqlParameter("#email", SqlDbType.NVarChar);
param2.Direction = ParameterDirection.Input;
param2.Value = username;
command.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#codemeli", SqlDbType.NChar);
param3.Direction = ParameterDirection.Input;
param3.Value = username;
command.Parameters.Add(param3);
// Return value as parameter
SqlParameter returnuser = new SqlParameter("#user", SqlDbType.NVarChar);
returnuser.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnuser);
SqlParameter returncode = new SqlParameter("#code", SqlDbType.NChar);
returncode.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returncode);
SqlParameter returnmail = new SqlParameter("#mail", SqlDbType.NVarChar);
returnmail.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnmail);
// Execute the stored procedure
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Thank you.
Set ParameterDirection=Output for #user,#code, and #mail and also specify the width/size/length of parameter.
SqlParameter returnuser = new SqlParameter("#user", SqlDbType.NVarChar,100);
returnuser.Direction = ParameterDirection.Output;
command.Parameters.Add(returnuser);

Categories