Home > Net >  How to compare the stored procedure's output?
How to compare the stored procedure's output?

Time:12-27

I want to check first if the user exists or not so I made a stored procedure in my SQL Server to check that.

CREATE PROCEDURE Login
    @username varchar(20), 
    @password varchar(20),
    @status int output
AS
    IF EXISTS (SELECT username, password 
               FROM SystemUser 
               WHERE username = @username AND password = @password)
        SET @status = 1
    ELSE
        SET @status = 0

Then, using ASP.NET Webforms, I'm creating a login page for the users

protected void login(object sender, EventArgs e)
{
    String connstr = WebConfigurationManager.ConnectionStrings["Sports"].ToString();

    SqlConnection conn = new SqlConnection(connstr);
            
    String username = txt_Username.Text;
    String password = txt_password.Text;

    SqlCommand login = new SqlCommand("userLogin", conn);
    login.CommandType = CommandType.StoredProcedure;

    login.Parameters.Add(new SqlParameter("@username", username));
    login.Parameters.Add(new SqlParameter("@password", password));

    SqlParameter loginstatus = login.Parameters.Add("@status", SqlDbType.Int);
    loginstatus.Direction = ParameterDirection.Output;

    conn.Open();
    login.ExecuteNonQuery();
    conn.Close();

    if (loginstatus.GetInt32 == 1)
    {
        Response.Write("hello");
        Response.Redirect("Home.aspx");
    }
}

However, I get an error:

Error CS1061 'SqlParameter' does not contain a definition for 'GetInt32' and no accessible extension method 'GetInt32' accepting a first argument of type 'SqlParameter' could be found (are you missing a using directive or an assembly reference?)

Any idea how can I compare the output from the stored procedure in the if condition?

Thanks in advance

I tried different types of methods like .value. Expecting to know how to compare the value to an int.

CodePudding user response:

you can get the value using .Value

if ((int)loginstatus.Value == 1)
{
    ...
}

There are other issues also in your code.

you are storing the password as plain text in a database table.

please use using with SqlConnection to dispose of automatically, same comment for SqlCommand .

and please use meaningful names when declaring variables like SqlCommand login. it's very unclear by the name login. it should be command or sqlCommand

  • Related