How do I cast Scope_Identity() to Int?
Asked Answered
D

3

12

So Scope_Identity() returns an ?-Byte Numeric Type in SQL Server.

That is not awesome.

Is there a safe way to cast it to an int in a select query so we don't have to manage every whim of SQL Server in our ODBC Wrapper?

Dharma answered 16/6, 2009 at 14:28 Comment(0)
C
18

If the source column to which the identity belongs is an Integer, there's no need to cast it. The following works just fine assuming the identity column is an Integer to begin with or it fits inside an "Int".

DECLARE @NewIdent Int
SET @NewIdent = SCOPE_IDENTITY()
Clad answered 16/6, 2009 at 14:32 Comment(2)
So the cast is taken care of in the process of assigning to NewIdent, but it's still casting.Cofferdam
It does not work for me, SQL2016, it just return decimal(18,0) for me , I had to convert it to intJuryrigged
C
13
SELECT CAST( bigintcolumn AS int )

(Provided you know it will fit into a 32bit integer)

Csc answered 16/6, 2009 at 14:31 Comment(1)
That's what I thought, I'm not sure why it doesn't work though. T'was returning 0.Dharma
C
4

Just cast this like:

select CAST(SCOPE_IDENTITY() as int)

And your data Layer:

reader.GetInt32(0);
Carlsbad answered 16/5, 2017 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.