Use @@IDENTITY to Return the Last-Inserted Identity Value in SQL Server

In SQL Server, you can use the T-SQL @@IDENTITY system function to return the last-inserted identity value in the current session.

Note that it returns the last identity value generated in any table in the current session. This is in contrast to the IDENT_CURRENT() function, which returns the last-inserted identity value for a given table.

The SCOPE_IDENTITY() function is very similar to @@IDENTITY in that it also returns the last-inserted identity value in the current session. The difference is that SCOPE_IDENTITY() is limited to the current scope.

Continue reading

11 Ways to Retrieve a Primary Key in SQL Server (T-SQL Examples)

There are often many ways to do the same (or similar) thing in SQL Server. Retrieving all primary keys from a database (or even just the primary key for a given table) is a case in point.

This article presents eleven different approaches to retrieving primary key information in SQL Server.

Some of these will be more useful than others, depending on your exact situation.

Continue reading

How to Replace NULL with Another Value in SQL Server – ISNULL()

When querying a SQL Server database, there may be times where you don’t want null values to be returned in your result set. And there may be times where you do want them returned. But there may also be times where you do want them returned, but as a different value.

That’s what the ISNULL() function is for.

ISNULL() is a T-SQL function that allows you to replace NULL with a specified value of your choice.

Continue reading