Saturday, 11 November 2006

SCOPE_IDENTITY() Returns Decimal

We use SCOPE_IDENTITY() function quite often to get the last identity value generated by Sql Server. What confuses me first is this function returns Decimal value. I have a sql insert stored procedure which has this last statement:

Select SCOPE_IDENTITY(),

The table has a auto incremental id field.

In my client code I have this:

int id = (int) command.ExecuteScalar(...)

Initially I thought I would read the integer id value without problem, but soon I got an InvalidCastException. And I discovered that the return value from DbCommand is of Decimal value type.

When I looked into MSDN, which is here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_sa-ses_6n8p.asp

I found out the return data type of this function is sql_variant. So the actual datatype could be any as Microsoft may change it in the future.

This is really interesting. To return an integer from stored procedure, we could cast it to integer as : Select CAST(SCOPE_IDENTITY() as Int) . This solves problem.

No comments: