SQLDataReader fails to throw exception

Viewed 1933

The function below was designed to determine if a query will return any rows. The passed in SQL is the query. If an error results the function should return false. However when SQL =

SELECT TOP 1 [AU_ID] 
       FROM [dat].[model_80av2_v1_2941] 
       WHERE [AU_ID] IS NOT NULL AND convert(int, [AU_ID]) <> [AU_ID]

the function mistakenly returns true since no error was detected. However executing the same query in SQL Management Studio results in an error:

Msg 232, Level 16, State 3, Line 3 Arithmetic overflow error for type int, value = -1000000000000000000000000000000.000000.

Clearly the function should have returned false because a value falls outside of the int data range but the error handling detects no error. Why? From other posts my understanding is that SqlDataReader reader = cmd.ExecuteReader() should result in an error.

private bool GetIfExists(string SQL, out int ErrorNumber, out bool Exists)
{
    bool IsSuccess = true;
    ErrorNumber = 0;
    Exists = false;

    try
    {
        using (SqlConnection cnn = new SqlConnection(_connectionString))
        {
            try
            {
                cnn.Open();

                using (SqlCommand cmd = cnn.CreateCommand())
                {
                    cmd.CommandText = SQL;
                    cmd.CommandTimeout = _commandTimeout;
                    try
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            Exists = reader.HasRows;
                        }
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Errors.Count > 0) ErrorNumber = ex.Errors[0].Number;
                        throw;
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                cnn.Close();
            }
        }
    }
    catch
    {
        IsSuccess = false;
    }
    return IsSuccess;
}
2 Answers
Related