Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a single value from SQL with ADO.NET

I am this far:

// Update status history if the current work flow item has a status
int workflowID = Convert.ToInt32(statusCode.SelectedValue);
string status = "select status from jm_accountworkflowdetail where workid = @workID";

SqlConnection sqlConnection2 = new SqlConnection(sqlDevelopment.ConnectionString);
SqlCommand sqlComm2 = new SqlCommand(status, sqlConnection2);

sqlComm2.Parameters.AddWithValue("@workID", workflowID);

The query will either return a value ('SOC', 'POS') or ('') meaning it didn't have a status attached.

What I need to do is if the status is not empty then perform some other code. But I'm not sure how to execute everything just to check if the status has a value or not.

like image 524
James Wilson Avatar asked Aug 06 '13 17:08

James Wilson


1 Answers

You need to use ExecuteScalar();

 string statusReturned = "";
 int workflowID = Convert.ToInt32(statusCode.SelectedValue);

 using (SqlConnection sqlConnection2 = new SqlConnection(sqlDevelopment.ConnectionString))
    {
        string status = "select status from jm_accountworkflowdetail where workid = @workID";
        SqlCommand sqlComm2 = new SqlCommand(status, sqlConnection2);
        sqlComm2.Parameters.AddWithValue("@workID", workflowID);
        try
        {
            sqlConnection2.Open();
            var returnValue = sqlComm2.ExecuteScalar()
                if returnValue != null then
                  statusReturned = returnValue.ToString();
        }
        catch (Exception ex)
        {
            //handle exception
        }
    }
    return statusReturned;

For checking the string value, you could have:

if (!String.IsNullOrEmpty(statusReturned)) {//perform code for SOC or POS}
like image 75
Christian Phillips Avatar answered Nov 15 '22 05:11

Christian Phillips