Wednesday, September 29, 2010

Blind Spot - T-SQL $Identity

I've been working with SQL Server for 12 years, but this short cut escaped me.

In Transact-SQL, the $IDENTITY keyword allows us to refer to the identity column without knowing its name. Since identity columns are often primary keys, we could use this as a short cut for always referring to the PK. This would be awesome to use in a code generator or an ORM.

This is not to be confused with @@IDENTITY or SCOPE_IDENTITY(), which tells us the actual number auto generated by the IDENTITY column (though each behaves in different ways.)

Test it out with this script:

use tempdb

create table test
id int identity(1,1)
, descr varchar(100)

insert into test
('first record')
, ('second record')
, ('third record')

select $identity, descr from test

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.