I have an update query(stored procedure) which is working properly in SQL Server when I execute it.
CREATE PROCEDURE updatestudenthws(#stdid nvarchar(50),#hwid int, #grade float)
AS
UPDATE Table_Exercise_Answer
SET
ExAns_Grade = #grade
WHERE ExAns_Exercise = #hwid AND ExAns_Student = #stdid
but when I run the program it does not have any effect in my table and also I don't have any error.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.VarChar);
cmd.Parameters.Add("#stdid", SqlDbType.VarChar);
cmd.Parameters.Add("#grade", SqlDbType.VarChar);
cmd.Parameters["#hwid"].Value = hwid;
cmd.Parameters["#stdid"].Value = studentid;
cmd.Parameters["#grade"].Value = grade;
cmd.ExecuteNonQuery();
con.Close();
What is my mistake?
How should I do this work?
Use AddWithValue(), so you don't have to provide the type, which allowed you to make the mistake of passing varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Your ADO.NET code defining the parameters for the stored procedure is wrong in that you don't define the parameters with their proper datatypes.
Your stored procedure defines:
#stdid nvarchar(50) --> but you define it as varchar
#hwid int --> but you define it as varchar
#grade float --> but you define it as varchar
You need to change your code to this:
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.Int); // this needs to be SqlDbType.Int
cmd.Parameters.Add("#stdid", SqlDbType.NVarChar, 50); // this should be SqlDbType.NVarChar and specify its proper length
cmd.Parameters.Add("#grade", SqlDbType.Float); // this needs to be SqlDbType.Float
when you use AddWithValue(), don't you have to provide the type passing like varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Related
When using this code, I get an error
Procedure or function 'Registration' expects parameter '#qUsername', which was not supplied
Can someone please tell me how to fix this? This is my controller code and the SQL query for registration
public ActionResult Create([Bind(Include = "UserID,Username,FirstName,LastName,Email,Password,Number,IsAdmin,Salt")] UsersTable usersTable)
{
if (ModelState.IsValid)
{
Int32 rowsAffected;
SqlCommand cmd = new SqlCommand();
SqlConnection sqlConnection1 = new SqlConnection(#"xxx");
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
return RedirectToAction("Index");
}
return View(usersTable);
}
Procedure code:
CREATE PROCEDURE dbo.Registration
#qUsername NVARCHAR(50),
#qPassword NVARCHAR(50),
#qFirstName NVARCHAR(40),
#qLastName NVARCHAR(40),
#errorResponse NVARCHAR(250) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #salt UNIQUEIDENTIFIER = NEWID()
BEGIN TRY
INSERT INTO dbo.UsersTable (UserID, Password, Salt, FirstName, LastName)
VALUES (#qUsername, HASHBYTES('SHA2_512', #qPassword + CAST(#salt AS NVARCHAR(36))), #salt, #qFirstName, #qLastName)
SET #errorResponse = 'Success'
END TRY
BEGIN CATCH
SET #errorResponse = ERROR_MESSAGE()
END CATCH
END
You need to define and set the parameters for the stored procedure before your call it from your C# code - like this:
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
// define and set parameters!
cmd.Parameters.Add("#qUsername", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qPassword", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qFirstName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#qLastName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#errorResponse", SqlDbType.NVarChar, 250).Direction = ParameterDirection.Output;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
Use the following:
cmd.Parameters.AddWithValue("#qUsername", "xxxxx");
For all parameters before calling:
cmd.ExecuteNonQuery();
I'm creating a page that inserts user information into a SQL server. I want to check to make sure that the database table doesn't already have the user EDIPI number in it and if it does not than it insert the new provided information. My error message is:
Procedure or function 'TestTableInsert' expects parameter '#EDIPI', which was not supplied.
My btnSaveSP_Click should allow the user to insert the information in to the database but I believe my Stored Procedure is wrong.
My Button Code:
protected void btnSaveSP_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand();
SqlCommand sqlCmd = new SqlCommand("TestTableInsert", sqlconn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
sqlCmd.ExecuteNonQuery();
sqlconn.Close();
}
My Stored Procedure code:
ALTER PROCEDURE [dbo].[TestTableInsert]
#EDIPI nvarchar(50),
#First nvarchar(50)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM TestTable where EDIPI = #EDIPI)
BEGIN
INSERT INTO TestTable (EDIPI,First)
VALUES (#EDIPI, #First)
END
END
You need to change
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
into
sqlCmd.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlCmd.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
Note that in the first you use sqlcomm while it should be sqlCmd
i have the following stored procedure in sql server and i am trying to take the permission value with C#.
CREATE PROCEDURE [dbo].[GetPermission]
#userName varchar(50),
#permission int output
AS
BEGIN
select #permission = PERMISSION from USERS where UserName = #userName
END;
My C# code is the following:
SqlCommand cmd = new SqlCommand(
"sp_getPermission", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter("#UserName", textBox1.Text));
cmd.Parameters.Add(
new SqlParameter("#permission", "none"));
SqlDataReader rdr = null;
rdr = cmd.ExecuteReader();
MessageBox.Show( rdr["Permission"].ToString() );
But i get the following error on the last line of C# code:
Invalid attempt to read when no data is present.
Any suggestions?
Let's simply this:
first, remove the output parameter #permission, then, change your procedure like this:
CREATE PROCEDURE [dbo].[GetPermission]
#userName varchar(50)
AS
BEGIN
select PERMISSION from USERS where UserName = #userName
END;
and for read the permission, use the ExecuteScalar method:
SqlCommand cmd = new SqlCommand(
"sp_getPermission", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter("#UserName", textBox1.Text));
var permission = (System.Int32)cmd.ExecuteScalar();
You need to set the ParameterDirection of the permission parameter on the SqlCommand to ParameterDirection.Output
Also, as you are not resulting a resultset, no need to use ExecuteReader. Just do:
cmd.ExecuteNonQuery();
You need to Read your SqlDataReader:
rdr = cmd.ExecuteReader();
if (rdr.HasRows()){
rdr.Read()
MessageBox.Show( rdr["Permission"].ToString() );
rdr.Close()
}
However, I don't believe you need a SqlDataReader for this situation. The following should work:
cmd.Parameters.Add(
new SqlParameter("#permission", "none"));
cmd.Parameters["#permission"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["#permission"].Value);
I am getting the following error while supplying parameters to a stored procedure:
Procedure or function 'ismovieexists' expects parameter '#movie_name', which was not supplied
and the same error message for the procedure insert_values_in_movie_master..
public int add_movie(mymovie objmymovie)
{
SqlConnection cn = new SqlConnection(_connectionstring);
cn.Open();
//SqlDataReader dr;
SqlCommand cmd = new SqlCommand("ismovieexists", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#movie_name", objmymovie.MOVIE_NAME);
SqlParameter d = new SqlParameter("#d", SqlDbType.Int);
d.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(d);
cmd.ExecuteReader();
int i = (int)cmd.Parameters["#d"].Value;
if (i == 0)
{
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = cn;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "insert_values_in_movie_master";
cmd1.Parameters.AddWithValue("#movie_name", objmymovie.MOVIE_NAME);
cmd1.Parameters.AddWithValue("#rating", objmymovie.RATING);
cmd1.Parameters.AddWithValue("#realease_year", objmymovie.REALEASE_YEAR);
cmd1.Parameters.AddWithValue("#starcast", objmymovie.STARCAST);
cmd1.Parameters.AddWithValue("#language", objmymovie.LANGUAGE);
cmd1.Parameters.AddWithValue("#display_home", objmymovie.DISPLAY_HOME);
cmd1.Parameters.AddWithValue("#block_status", objmymovie.BLOCK_STATUS);
cmd1.Parameters.AddWithValue("#no_of_copies", objmymovie.no_of_copies);
cmd1.Parameters.AddWithValue("#MOVIE_category", objmymovie.MOVIE_category);
cmd1.Parameters.AddWithValue("#MOVIE_flag", objmymovie.MOVIE_FLAG);
cmd1.ExecuteNonQuery();
return i;
}
else
return 1;
}
Does the parameter #Movie_Name exist in your Stored Procedures? If the parameter does exist it's likely that you are not passing a value to objmymovie.MOVIE_NAME
I have a stored procedure with an output parameter. How do I read this value using C# code?
I assume you use ADO.NET? If so, the SqlParameter class has the property "Direction". Set direction to output and after the query has executed you read the value from that parameter.
Something like this:
using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("#pkid", SqlDbType.Int);
parm.Value = 1;
parm.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm);
SqlParameter parm2 = new SqlParameter("#ProductName", SqlDbType.VarChar);
parm2.Size = 50;
parm2.Direction = ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm2);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}