I'm working with SQL now in my programming, and I'm q开发者_StackOverflow中文版uerying a database, like so.
scCommand = new SqlCommand("SELECT LegislationID FROM Legislation WHERE Number = @ECERegulation", sconConnection);
scCommand.Parameters.Add("@ECERegulation", SqlDbType.NVarChar);
scCommand.Parameters["@ECERegulation"].Value = strECERegulation;
return (int)scCommand.ExecuteScalar();
My question is, what would be returned if my parameter did not match anything in the table that I am querying? I need to have an if statement to deal with a non-matching ECERegulation. Would it return null? Or would it return the LegislationID of zero? Any help would be appreciated.
The docs:
Return Value
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
If no record is found, it would return NULL
. So you would get a casting error.
You need to check the result for nullity before casting. And also decided whether to throw an exception or return zero, depending on your business rules.
You can match the null by using Nullable< int >. You can also pass the casting error and return null like this.
int? GetSomething()
{
.....
.....
return (int?)TypeDescriptor.GetConverter(typeof(int?)).ConvertFrom(scCommand.ExecuteScalar());
}
精彩评论