SQL Interview: How to Insert value in identity column in SQL Server 2012

Most Important SQL Server Interview Question...
How to Insert value in identity column manually/forcefully?

This is the script which will describe you how to insert identity column value 
Script:
GO
--Create a table with identity Column
CREATE TABLE tbl_ID_Insert(ID INT IDENTITY(1,1),Name VARCHAR(50))
GO
--Add 5 values
INSERT INTO tbl_ID_Insert(Name) VALUES('Vikas'),('Deepak')
,('Ashutosh'),('Rohit'),('Nitin')
SELECT * FROM tbl_ID_Insert
GO
--Delete a record with id 2
DELETE FROM tbl_ID_Insert WHERE ID = 2
SELECT * FROM tbl_ID_Insert
GO
-- Now Forcefully Insert new record, with same ID as last

SET IDENTITY_INSERT tbl_ID_Insert ON

INSERT INTO tbl_ID_Insert(ID,Name) VALUES(2,'DEEPAK')
SELECT * FROM tbl_ID_Insert
GO
DROP TABLE tbl_ID_Insert
GO

Comments

Archive

Contact Form

Send