I learned that SQL Server can return the value of the (single) identity column of a table using the pseudo-column $IDENTITY
:
SELECT $IDENTITY FROM Table
Is this feature documented and reliable? The only official mention of it is on the IDENTITY
page but it's buried in a code sample. This suggest that it might be intended to be undocumented. There are remarkably few Google matches for this feature as well.
Best Answer
$IDENTITY
(and$ROWGUID
) are documented in SELECT Clause (Transact-SQL).I would caution against using it because it will throw an error when a table doesn't have an identity column. Take these two examples - the first one works (check your Results tab), but the second one throws an error:
Here's what the second one produces:
If you're looking to find which columns have an identity field, I'd use the method described in this Stack Overflow post instead:
Or, using the catalog views: