Wednesday, November 19, 2014

IDENTITY Property in SQL server

-- This will be all about Identity Column...

* Identity Column will generate the number automatically for the row..Based on where you are starting the numbers and declaring the increment as below
Identity(Seed,Increment): IDENTITY(1,1)
So it starts the number with 1 and for the next number it will increment the orginal number by 1 So it should be 2
1
2
3
.
.
.
n
-- Can you insert manually the number?
Yes, by turning of the IDENTITY_INSERT ON

--Is there any precausions we need to follow to insert manually?
Yes, Make sure mention all columns/ Identity column(depends on requirement) in the insert statement

Correct_Version : INSERT INTO IDTable (IDNo, Name) SELECT 1,'pan'

Wrong_Version : INSERT INTO IDTable SELECT 1,'Pan'

-- Sample table ? and sample data in Identity Table?

CREATE TABLE IDTable( IDNo INT IDENTITY(1,1), Name VARCHAR(20))
INSERT INTO IDTable VALUES ('1st record')
-- How to reset Identity ?
Syntax : DBCC CHECKIDENT ('TableName',RESEED,NewstartingPosition)
Ex : DBCC CHECKIDENT ('IDTable',RESEED,15)

-- How to find the current identity value of the table?
        SELECT IDENT_CURRENT( 'IDTable' )
-- If you truncate the identity Column table, what would be the next identity value?
        TRUNCATE Table IDTable
          
Truncate will reset the Values to starting position of the Create statement.
So It populate the value what ever the seed value you declared during the table creation and follows as the increment for the next rows.

-- If you Delete the identity Column table, what would be the next identity value?

        DELETE FROM IDTable

It will delete the records. When you are inserting the values next time It will start from where it stopped last time.
It does not matter those records already been deleted.

No comments:

Post a Comment