When is 19 Not an Integer

J

Jonathan Wood

Er... When it's a Decimal.

I'm executing a query that includes the following: "INSERT INTO [...];
SELECT SCOPE_IDENTITY()"

I then attempt to retrieve the scope identity with code that looks like
this:

int contractId = (int)cmd.ExecuteScalar();

I get an "Invalid cast" error. Examing the value returned by
ExecuteScalar(), I see it is 19 and of type Decimal.

Can anyone explain to me why a Decimal with a value of 19 cannot be cast to
an integer?

Thanks.

Jonathan
 
H

Hans Kesting

Jonathan Wood has brought this to us :
Er... When it's a Decimal.

I'm executing a query that includes the following: "INSERT INTO [...]; SELECT
SCOPE_IDENTITY()"

I then attempt to retrieve the scope identity with code that looks like this:

int contractId = (int)cmd.ExecuteScalar();

I get an "Invalid cast" error. Examing the value returned by ExecuteScalar(),
I see it is 19 and of type Decimal.

Can anyone explain to me why a Decimal with a value of 19 cannot be cast to
an integer?

Thanks.

Jonathan

The value returned by ExecuteScalar is an object, in this case a boxed
decimal. You can only unbox it to the exact type, even though the value
(19) could (now) fit in an integer.

This would work: int contractId = (int)(decimal)cmd.ExecuteScalar();

First unbox the returned decimal and *then* cast it to an integer.

Hans Kesting
 
N

Norman Yuan

The real question is why SCOPE_IDENTITY() returns a decimal value.

Usually, when design a table, a column is set as Identity, its data type is
integer, however, you can also set the column's data type as decimal with
scale=0 and still set Identity=True.

So, it must be that the table's Identity column's data type is decimal. Go
check the table's design.

If the column is decimal type, then like other replies pointed out, you
cannot directly cast cmd.ExecuteScalar()'s returning value with
(int)cmd.ExecuteScalar()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top