Search code examples
asp.netmysql-error-1064

Table expects a parameter which already exists


ALTER PROCEDURE tableuser
    -- Add the parameters for the stored procedure here
    @userName varchar(50)
AS
IF EXISTS(SELECT 'True' FROM tbl_user WHERE userName = @userName)
BEGIN
  --This means it exists, return it to ASP and tell us
  SELECT 'This record already exists!'
END
ELSE
BEGIN
  --This means the record isn't in there already, let's go ahead and add it
  SELECT 'Record Added'
  INSERT into tbl_user(userName) VALUES(@username)
END

This is my code in sql server management studio and below is the C# code:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("tableuser", conn);
    conn.Open();
    SqlParameter param = new SqlParameter();
    cmd.Parameters.AddWithValue("@userName", uname.Text);
    param.Value = uname.Text;

    cmd.Parameters.Add(param);

    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
       Response.Write("Username exists");
    }
    else
    {
        cmd.Parameters.AddWithValue("@userName", uname.Text);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        conn.Open();
        cmd.ExecuteNonQuery();
        Response.Write("Successfully saved...!!!");
        conn.Close();
    }
}

}

The error comes is: Procedure or function 'tableuser' expects parameter '@userName', which was not supplied.


Solution

  • This should work:

    conn.Open();
    var cmd = new SqlCommand("tableuser", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@userName", uname.Text);
    
    var rdr = cmd.ExecuteReader();
    
    rdr.Read();
    Response.Write(rdr.GetString(0));
    conn.Close();