Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does select SCOPE_IDENTITY() return a decimal instead of an integer?

So I have a table with an identity column as the primary key, so it is an integer. So, why does SCOPE_IDENTITY() always return a decimal value instead of an int to my C# application? This is really annoying since decimal values will not implicitly convert to integers in C#, which means I now have to rewrite a bunch of stuff and have a lot of helper methods because I use SQL Server and Postgres, which Postgres does return an integer for the equivalent function..

Why does SCOPE_IDENTITY() not just return a plain integer? Are there people out there that commonly use decimal/non-identity values for primary keys?

like image 780
Earlz Avatar asked Apr 08 '10 16:04

Earlz


People also ask

What is the return type of Scope_identity ()?

The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.

What is the difference between Scope_identity () identity () @@ Identity and Ident_current ()?

The @@identity function returns the last identity created in the same session. The scope_identity() function returns the last identity created in the same session and the same scope. The ident_current(name) returns the last identity created for a specific table or view in any session.

What is the use of @@ identity and Scope_identity?

@@IDENTITY is not limited to a specific scope. SCOPE_IDENTITY() - Return the last identity values that are generated in any table in the current session. SCOPE_IDENTITY returns values inserted only within the current scope.

Can we add identity column to decimal data type?

Only columns of type SMALLINT, INTEGER, BIGINT, DECIMAL, or NUMERIC can be created as identity columns. You are allowed only one identity column per table. When you are changing a table definition, only a column that you are adding can be specified as an identity column; existing columns cannot.


2 Answers

In SQL Server, the IDENTITY property can be assigned to tinyint, smallint, int, bigint, decimal(p, 0), or numeric(p, 0) columns. Therefore the SCOPE_IDENTITY function has to return a data type that can encompass all of the above.

As previous answers have said, just cast it to int on the server before returning it, then ADO.NET will detect its type as you expect.

like image 127
Christian Hayter Avatar answered Oct 16 '22 09:10

Christian Hayter


Can't you just cast it before returning it from your query or stored proc (SPs alway return int anyway, but maybe you are using an output parameter)?

Like SELECT CAST(SCOPE_IDENTITY() AS INT) AS LAST_IDENTITY

And why it does this? Probably to be more flexible and handle larger numbers.

like image 39
Cade Roux Avatar answered Oct 16 '22 10:10

Cade Roux