SQL Server – Altering IDENTITY Values

When a new record is added to a table, SQL Server generates a unique number using the IDENTITY keyword. This is the primary key field where we want to insert a sequence number or a row number to address that specific row.

The IDENTITY can be specified with a starting value and an incremental value, both of which must be numerical values. If no starting and incremental values are specified, SQL Server will allocate (1,1), which means the first value will be 1 and incremented by 1.

Because the column is auto-generated, it should be skipped from the INSERT statement once it has been assigned with IDENTITY.

Once assigned the identity value cannot be modified however there’s an alternative. Look at the below example.

— Creating the table with Auto-generated values.
CREATE TABLE [SampleData] (

[IDCol] INT IDENTITY(201801,1),
[StringCol] VARCHAR(100) DEFAULT ‘BigDatanSQL’,
[DateCol] DATETIME DEFAULT GETDATE());
GO

— Inserting 12 rows, in loop.

INSERT INTO [SampleData] DEFAULT VALUES;
GO 12

SELECT * FROM SampleData

SQLServer_IdentityValue

— Now, if the identity value needs to be modified to something else, then
SET IDENTITY_INSERT SampleData ON
     INSERT INTO SampleData(IDCol)VALUES(201901)
SET IDENTITY_INSERT SampleData OFF
GO

— Inserting 11 rows, in loop.
INSERT INTO [SampleData] DEFAULT VALUES;

GO 11

SELECT * FROM SampleData

SQLServer_IdentityValue2

Hope you find this post helpful.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s