views:

200

answers:

1

I had an odd problem, here's the setup:

ASP.NET 3.5 app / MSSQLSERVER 2008 back-end.

I called ExecuteScalar from my code, which returned an object, then I tried casting that object to int (i actually have a generic method

 T ConvertDBValue<T>(object o) {...}

, but that's not as important).

ExecuteScalar is hitting the following sproc:

...  
insert into ...
select scope_identity()

My primary key is an identity field, and returned 85. Next thing I got is InvalidCastException trying to cast 85 to int.

The solution was to explicitly create an INT variable, and assign SCOPE_IDENTITY() to it before returning it from the sproc as follows:

...  
DECLARE @x int
insert into ...
select @x = scope_identity()
select @x

Can somebody tell me what was the problem with my first approach, and why wouldn't it cast 85 to int?

+4  A: 

scope_identity() actually returns a (TSQL) BIGINT (I've been caught by this before!)

So your code was trying to cast a BIGINT to an int.

Mitch Wheat
where is this documented?
roman m
See section in the link that says return types...
Mitch Wheat
It says it returns `numeric(38,0)`, not `bigint`? Either way, you can work around this a few ways, in either your code or in the SQL. In the SQL, you can do this `SELECT CAST(SCOPE_IDENTITY() as int)`, or in your C#, you can do this `int x = Convert.ToInt32(whatever)`. But, as the original poster discovered, using output or return parameters would of course negate the need for this...
Funka