I am trying to understand what is wrong with this select. I want to get the last user_Id which was been added.
Here is the error message: The parameterized query '(@Id_user int)SELECT SCOPE_IDENTITY() AS id_user' expects the parameter '@Id_user', which was not supplied.
Here is the SQL statement:
if (count >= 1) /* <=== verification from the insert SQL */
{
string selectStatement = "SELECT SCOPE_IDENTITY() AS id_user";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
selectCommand.Parameters.Add("@Id_user", SqlDbType.Int, 0, "Id_user");
int newID = (int)selectCommand.ExecuteScalar();
int User_ID = Convert.ToInt32(selectCommand.Parameters["@Id_user"].Value);
Session["Id_user"] = User_ID;
buserIdAuthenticated = true;
Session["userIdAuthenticated"] = buserIdAuthenticated;
Response.Redirect("../pages/Welcome.aspx");
}
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
sqlConnection.Close();
}
you haven't defined an @parameter in your sql statement so you don;t need to add the parameter at all - just get the result of ExecuteScalar - you should be able to cast it to an int - although I cast it specifically in the sql statement too -
select cast(Scope_identity() as int) ....
so you'd end up with somthing like
string selectStatement = "SELECT cast(SCOPE_IDENTITY() AS int)";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
object newIDobj = (int)selectCommand.ExecuteScalar();
if(newIDobj!=null)
Session["Id_user"] = (int)newIDobj;
Even better you could create a stored procedure and have the insert done there, where it can then return scope identity.
Edited to include example with insert. (just typed in here - so likely some typos)
int newID = -1;
string commandString = "insert (code, desc, numbervalue) values (@code, @desc,@numbervalue); select cast(scope_identity() as int);"
using(SqlCommand cmd = new SqlCommand(commandString))
{
try
{
cmd.Parameters.Add("@code", )
// etc
int newid=(int)(cmd.ExecuteScalar()??-1);
}
catch(Exception e)
{
// something went wrong
}
}
if(newID!=-1)
{
// do something;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.