I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.
So I tried to use the SqlCommand to query a table that has data:
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)
When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?
I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(
My code looks like this:
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 SqlParame开发者_开发知识库ter("@State", 1 /* active */));
byte retValue = (byte)sqlCommand.ExecuteScalar();
return retValue;
}
}
THANKS!
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.
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
精彩评论