0

Trying to do the following:

 public static int GetJobStatusByNumber(int jobNumber)
    {
        SqlConnection connection = null;
        try
        {
            connection = new SqlConnection(connString);
            connection.Open();

            SqlCommand cmd = connection.CreateCommand();
            cmd.CommandText = @"select STATUS  from JOB
                                where JOB_NUMBER = @jobNumber";

            cmd.Parameters.AddWithValue("@jobNumber", jobNumber);

            int result = ((int)cmd.ExecuteScalar());
            return result;
        }

        finally
        {
            if (connection != null)
                connection.Close();
        }
    }

Thouht I can add the varible 'jobNumber' to the query by using 'AddWithValue' but I'm getting a cast error

Message: System.InvalidCastException : Specified cast is not valid.

What's wrong here?

Thanks.

2
  • is STATUS an integer? ExecuteScalar returns the first column value from the first row, regardless of type, so if it gets back, say, a string, then the cast to int will fail. Commented May 3, 2019 at 0:57
  • Oh, true. Changed to string. An oversight...;-) Commented May 3, 2019 at 1:07

1 Answer 1

2

ExecuteScalar() returns the first column of the first row in the result set returned by the query.

2 scenarios are possible:

  1. the first column is not a int.
  2. the query return 0 rows - in that case ExecuteScalar() will return null.

for point 1 - make sure that the first column is an int.
for point 2 - make sure you have rows. possible solution will be:

var result = 0;
var tempResult = cmd.ExecuteScalar();

if (tempResult != null) {
    result = (int)tempResult;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.