4

I have this sql parameter im getting the cant unbox as int error

returnValue = (int)cmdUpdateCreatedOn.Parameters["@intcount"].Value;

return value is declared as int returnValue = 0 and my parameter is also declared as int, and it is getting the rowcount of rows updated. I've tried different converting syntax none seem to work.

MY SP is

ALTER Procedure [dbo].[UpdateStation]
@intcount int output AS 
select StationaryName into #stname from Stationaries where Authorized = 0 
select * from #stname 
Update Stationaries Set  Authorized = 1 where Authorized = 0 set @intcount =   @@rowcount
peterh
  • 11,875
  • 18
  • 85
  • 108
CSharper
  • 5,420
  • 6
  • 28
  • 54
  • 6
    Look at the value in the debugger. What is the value? What is its type? My money's on the value either being a nullable int or actually being `null`, but regardless of the issue, it's trivial to solve. – Servy Aug 05 '13 at 15:47
  • 1
    What *exact* error are you getting? – Jon Skeet Aug 05 '13 at 15:48
  • in the debugger its value is an int, and it says, cannot unbox 'cmdUpdateCreatedOn.Parameters["@intcount"].Value' as an int – CSharper Aug 05 '13 at 15:51
  • Try this and tell us what the value of `type` is: `var type = cmdUpdateCreatedOn.Parameters["@intcount"].Value.GetType();` – Daniel Hilgarth Aug 05 '13 at 15:53
  • my returnValue is an int but it saying that the expression is an object – CSharper Aug 05 '13 at 15:53
  • 2
    Are you sure you're getting an `int` back from the database? Unboxing requires you to unbox to the original type it was boxed from before casting it to the desired type. Is there a chance you boxed it, or the DB is boxing, to a different value type? – keyboardP Aug 05 '13 at 15:53
  • this is my stored procedure – CSharper Aug 05 '13 at 15:56
  • ALTER Procedure [dbo].[UpdateStation] "atsign"intcount int output AS select StationaryName into #stname from Stationaries where Authorized = 0 select * from #stname Update Stationaries Set Authorized = 1 where Authorized = 0 set "atsign"intcount = "atsign""atsign"rowcount – CSharper Aug 05 '13 at 15:58
  • 1
    u better put that as an update in your question csharper. – terrybozzio Aug 05 '13 at 16:01
  • what is your rowcount type? @@rowcount? – terrybozzio Aug 05 '13 at 16:15
  • Have a look here: http://stackoverflow.com/questions/8771476/c-sharp-issues-with-boxing-unboxing-typecasting-ints-i-dont-understand The question is: is the returned value really an Int32? May be some other int? – Zverev Evgeniy Aug 05 '13 at 16:45

1 Answers1

8

I had the same issue.

The INT being returned in stored procedure is of type 'SHORT'. I do not know why.

Cannot cast ..."@SubjectID"... (which has an actual type of 'short') to 'string'.

Solution:
1. Unbox to 'SHORT' in c# OR
2. Use Convert.ToInt32 in c#.

Pramod Mangalore
  • 536
  • 5
  • 18