Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Newbie question on SCOPE_IDENTITY
Message
General information
Forum:
Microsoft SQL Server
Category:
Other
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01196646
Message ID:
01196675
Views:
16
>I am pretty sure I used the following syntax before, in another program. And it worked there. Now I am using the following code to get the PK value of the newly inserted row:
>
>
>SQLEXEC( hCon,"select SCOPE_IDENTITY() AS nValue","cur_identity")
>nCompPk = cur_identity.nvalue
>
>
>But the value of nCompPk and cur_identity.nvalue is NULL.
>
>What am I missing?

From BOL:

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.



Every SQLEXEC() is different batch, so you can't use SCOPE_IDENTITY() in separate SQLEXEC(). If you want to use it you must embed it in the same SQLEXEC() with INSERT:
TEXT TO lcInsert NOSHOW TEXTMERGE
     INSERT INTO ............
     SELECT SCOPE_IDENTITY()
ENDTEXT
SQLEXEC(..., lcInsert, [crsIDColumn])
SELECT crsIDColumn
BROWSE NORMAL
But keep in mind that if you have more than one record inserted that query will return you the LAST IDENTITY value inserted.
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform