Pregunta

He hecho un poco de investigación antes de publicar esta pregunta y yo soy consciente del hecho de que cuando hay no devolvió datos, ExecuteScalar arrojará un System.NullReferenceException. Es por eso que he modificado mi procedimiento almacenado al "retorno 1" por lo que está garantizado un valor de retorno. Sin embargo, todavía estoy consiguiendo la excepción de referencia NULL.

Así que traté de usar el SqlCommand para consultar una tabla que tiene los datos:

        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)

Cuando me encontré ejecutar escalar pude recoger a un valor por lo que sé que tengo el permiso para consultar la base de datos. Estoy sospechando que esto es una opción de permiso proc storeed específica que echaba de menos?

Te lo agradecería cualquier comentario / sugerencias que he estado pegado en esto por un día de estos. : (

Mi código es el siguiente:

        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                //sqlCommand.Parameters.Add(new SqlParameter("@Id", this.ID));
                //sqlCommand.Parameters.Add(new SqlParameter("@State", 1 /* active */));

                byte retValue = (byte)sqlCommand.ExecuteScalar();
                return retValue;
            }
        }

GRACIAS!

¿Fue útil?

Solución

Random guess

You are using RETURN so there is no dataset to read column 1, row 1 for ExecuteScalar

Use SELECT or OUTPUT parameters

Edit: Actually, not so random

RETURN 1 is not a result set: it's a "special" parameter

sqlCmd.Parameters.Add(New SqlParameter("RETURN_VALUE", SqlDbType.Int)).Direction = ParameterDirection.ReturnValue

Otros consejos

I'm just going to elaborate on what @gbn said. When you execute SQL code you can return information in three different ways, OUTPUT parameters, tabular data and/or a single RETURN value. Like @gbn said, RETURN values are essentially specialized OUTPUT parameters. ExecuteScalar only sees information from tabular data, namely the first column of the first row. If no tabular data is received when you call ExecuteScalar a null value is returned instead. If you try to do something with this null value then obviously you'll get a NRE.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top