Skip to main content

IDENTITY in SQL Server

If you haven't heard about $IDENTITY in SQL Server check out the initial part of the scripts explained below to know what it does.

CREATE TABLE IdentityTest
(
  Sno INT IDENTITY(1,2) PRIMARY KEY,
CreatedDate DATETIME
)
GO


INSERT INTO IdentityTest(CreatedDate) 
SELECT Getdate()
Go 10

1. How to display the LAST inserted IDENTITY Value into a table in the current scope and session?
SELECT SCOPE_IDENTITY()

Generally we would use SCOPE_IDENTITY() but since SQL Server 2005 there is a serious bug with this. The safe option to use is OUTPUT clause. Check out this KB article here.

2. What if we don't know the IDENTITY column name but wanted to display its column values? (OR) Without mentioning the IDENTITY column name how to list all the IDENTITY values in a table?
SELECT $IDENTITY FROM IdentityTest
GO

I have seen $IDENTITY working since SQL Server 2005 and above. Not very sure whether it used to work in earlier versions as I have never tried this prior to SQL 2005.

3. How to check the current Identity seed value?
DBCC CHECKIDENT (IdentityTest)
GO

Checking identity information: current identity value '19', current column value '19'.

So while a new row is inserted it would be
"Current Column Value" (19) + STEP Value mentioned in IDENTITY declaration (2)

4. What happens if the transaction fails?

BEGIN TRANSACTION
INSERT INTO IdentityTest(CreatedDate) SELECT Getdate()
ROLLBACK TRANSACTION

Though the transaction is rolled back the "current column value" would have been increased by now! Check out DBCC CHECKIDENT to verity it

DBCC CHECKIDENT (IdentityTest)
GO

Checking identity information: current identity value '21', current column value '21'.

Let's try to INSERT another row into the table.

INSERT INTO IdentityTest(CreatedDate) 
SELECT Getdate()
GO


SELECT $IDENTITY FROM IdentityTest
GO

We can see that after 19 the identity value inserted is 23.

5. Assume we don't want that gap and want to insert a row with identity value 21 manually. How to do it?
--Option1:
--Immediately after the transcation failed may be we could have RESEED it back.
DBCC CHECKIDENT ("dbo.IdentityTest", RESEED, 19);
GO


--Option 2:
SET IDENTITY_INSERT IdentityTest ON

--You need to mentioned the column list else the statement would fail
INSERT INTO IdentityTest (Sno, CreatedDate)
SELECT 21, Getdate()
GO

SET IDENTITY_INSERT IdentityTest OFF

6. How to list all IDENTITY columns in a database?

SELECT 
OBJECT_NAME(OBJECT_ID) AS [Table Name], 
[Name] AS [Identity Column Name],
[seed_value] AS [Seed Value],
[Increment_value] AS [Increment Value],
[Last_Value] AS [Last Value]
FROM 
sys.identity_columns

7. Is it possible to UPDATE a value of an IDENTITY column?

NO. We cannot update an IDENTITY column. If we try to do so it would throw up an error.

SET IDENTITY_INSERT IdentityTest ON


UPDATE IdentityTest SET Sno = 31
WHERE Sno = 21
GO


SET IDENTITY_INSERT IdentityTest OFF

The error message would be something like this:
Msg 8102, Level 16, State 1, Line 4
Cannot update identity column 'Sno'.

8. Is it possible to generate Identity values as NEGATIVE values?

YES it is possible. In the below example it would start from 1 and start decreasing by -1 for each record.

CREATE TABLE IdentityTest_Negative
(
  Sno INT IDENTITY(1,-1) PRIMARY KEY,
  CreatedDate DATETIME
)
GO


INSERT INTO IdentityTest_Negative(CreatedDate) 
 SELECT Getdate()
GO 10


SELECT * FROM IdentityTest_Negative

Related topic written in 2004 - Fetching Identity Value

Comments

Bhaskara said…
Informative post

Popular posts from this blog

Registry manipulation from SQL

Registry Manupulation from SQL Server is pretty easy. There are 4 extended stored procedure in SQL Server 2000 for the purpose of manupulating the server registry. They are: 1) xp_regwrite 2) xp_regread 3) xp_regdeletekey 4) xp_regdeletevalue Let us see each one of them in detail! About xp_regwrite This extended stored procedure helps us to create data item in the (server’s) registry and we could also create a new key. Usage: We must specify the root key with the @rootkey parameter and an individual key with the @key parameter. Please note that if the key doesn’t exist (without any warnnig) it would be created in the registry. The @value_name parameter designates the data item and the @type the type of the data item. Valid data item types include REG_SZ and REG_DWORD . The last parameter is the @value parameter, which assigns a value to the data item. Let us now see an example which would add a new key called " TestKey ", and a new data item under it called TestKeyValue :

Screen scraping using XmlHttp and Vbscript ...

I wrote a small program for screen scraping any sites using XmlHttp object and VBScript. I know I haven't done any rocket science :) still I thought of sharing the code with you all. XmlHttp -- E x tensible M arkup L anguage H ypertext T ransfer P rotocol An advantage is that - the XmlHttp object queries the server and retrieve the latest information without reloading the page. Source code: < html > < head > < script language ="vbscript"> Dim objXmlHttp Set objXmlHttp = CreateObject("Msxml2.XMLHttp") Function ScreenScrapping() URL == "UR site URL comes here" objXmlHttp.Open "POST", url, False objXmlHttp.onreadystatechange = getref("HandleStateChange") objXmlHttp.Send End Function Function HandleStateChange() If (ObjXmlHttp.readyState = 4) Then msgbox "Screenscrapping completed .." divShowContent.innerHtml = objXmlHttp.responseText End If End Function </ script > < head > < body > &l

Script table as - ALTER TO is greyed out - SQL SERVER

One of my office colleague recently asked me why we are not able to generate ALTER Table script from SSMS. If we right click on the table and choose "Script Table As"  ALTER To option would be disabled or Greyed out. Is it a bug? No it isn't a bug. ALTER To is there to be used for generating modified script of Stored Procedure, Functions, Views, Triggers etc., and NOT for Tables. For generating ALTER Table script there is an work around. Right click on the table, choose "Modify" and enter into the design mode. Make what ever changes you want to make and WITHOUT saving it right click anywhere on the top half of the window (above Column properties) and choose "Generate Change Script". Please be advised that SQL Server would drop actually create a new table with modifications, move the data from the old table into it and then drop the old table. Sounds simple but assume you have a very large table for which you want to do this! Then it woul