Home > DeveloperSection > Forums > Using if statement to check individual value returned from a query
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    March-25-2015 7:36 AM

 JavaScript JQuery 
Ratings:


 1 Reply(s)
 575  View(s)
Rate this:

I have a seleect query which the return query is used in an if statement.

 

The query is correct, but the problem is becuase the query returns value from multiple rows it doesnt work.

 

I want to use the if statement to check individual values retrived by the query.

 

string security = "SELECT ProjectId FROM Project_List WHERE (ProfileId = (SELECT ProfileId FROM User_Profile WHERE (UserId = @UserId)))";

using (SqlConnection myConnection = new SqlConnection(connectionString))

{

    myConnection.Open();

    SqlCommand myCommand = new SqlCommand(security, myConnection);

    myCommand.Parameters.AddWithValue("@UserId", currentUserId);

 

    if (Request.QueryString["ProjectId"] == myCommand.ExecuteReader().ToString())

    {

 

    }

    else

    {

         Response.Redirect("projectlist.aspx");

    }

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-25-2015 7:47 AM

Instead of ExecuteScalar, which, as it's name implies returns a single value, you have to use ExecuteReader:

 

SqlDataReader reader = myCommand.ExecuteReader();

while (reader.Read())

{

   // grab next record selected

   int project_id = (int) reader[0];

 

   // do whatever you want with it

   if (Request.QueryString["ProjectId"] == project_id.ToString())

   {

 

   }

   else

   {

       Response.Redirect("projectlist.aspx");

   }

}

The while loop will traverse all records returned by the SELECT query and exit as soon as there no more records available.


Don't want to miss updates? Please click the below button!

Follow MindStick