Reputation: 5249
I am trying to store a select statement result in C# variable but getting this error
"Specified cast is not valid"
when i run it. I am not sure how to resolve it please help
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd1 = new SqlCommand("select cast(round(sum(CAST(AvgNumbers AS numeric(12,2))),2) as decimal(12,2)) AS [Average Days] from MainTable ", con1);
cmd1.Connection = con1;
con1.Open();
Int32 result = (Int32)cmd1.ExecuteScalar();
con1.Close();
Upvotes: 3
Views: 5265
Reputation: 98858
Your result isn' an Int32
obviosly, so you can use it;
var result = cmd1.ExecuteScalar();
After that, you can check it out which type it is. Or use;
object result = cmd1.ExecuteScalar();
Than maybe you can cast it. Just remember, you can look it in debugger easyly.
Upvotes: 1
Reputation: 109822
cmd1.ExecuteScalar()
is not returning a boxed integer. Assign it to an object and look at it in the debugger to see what it really is.
I'm guessing it's going to be returning a Decimal or a double, and you need to do:
Int32 result = (Int32)(double)cmd1.ExecuteScalar();
Or:
Int32 result = (Int32)(Decimal)cmd1.ExecuteScalar();
[EDIT in response to a question in commments below]
To keep the decimal value, just do this:
Decimal result = (Decimal) cmd1.ExecuteScalar();
If you needed to, you could cast the decimal to a double:
double result = (double)(Decimal) cmd1.ExectuteScalar();
Upvotes: 5
Reputation: 1503419
The result isn't an Int32
, basically. You're casting it to Decimal(12, 2)
- so I'm not sure why you'd expect it to.
My guess is that it'll either be a double
or a decimal
- but if you separate the call from the cast and look in the debugger, it should be obvious:
object result = cmd1.ExecuteScalar();
// Now look at the type of the value of result
Upvotes: 1
Reputation: 880
You're casting the value as a decimal in the SQL, so try casting as a decimal in your c# code.
Upvotes: 0